golang json復号符号化の概要

9238 ワード

符号化が必要な復号タイプ1が知る.エンコーディング
json.NewEncoder(<Writer>).encode(v)
json.Marshal(&v)

2.復号
json.NewDecoder(<Reader>).decode(&v)
json.Unmarshal([]byte, &v)

使用例
package main

import (
    "encoding/json"
    "fmt"
    "bytes"
    "strings"
)

type Person struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

func main()  {
    // 1.    json.Marshal   
    person1 := Person{"  ", 24}
    bytes1, err := json.Marshal(&person1)
    if err == nil {
        //          []byte
        fmt.Println("json.Marshal     : ", string(bytes1))
    }

    // 2.    json.Unmarshal   
    str := `{"name":"  ","age":25}`
    // json.Unmarshal         ,          []byte   
    bytes2 := []byte(str) //           
    var person2 Person    //           
    if json.Unmarshal(bytes2, &person2) == nil {
        fmt.Println("json.Unmarshal     : ", person2.Name, person2.Age)
    }

    // 3.    json.NewEncoder   
    person3 := Person{"  ", 30}
    //         buffer
    bytes3 := new(bytes.Buffer)
    _ = json.NewEncoder(bytes3).Encode(person3)
    if err == nil {
        fmt.Print("json.NewEncoder     : ", string(bytes3.Bytes()))
    }

    // 4.    json.NewDecoder   
    str4 := `{"name":"  ","age":28}`
    var person4 Person
    //      string reader     
    err = json.NewDecoder(strings.NewReader(str4)).Decode(&person4)
    if err == nil {
        fmt.Println("json.NewDecoder     : ", person4.Name, person4.Age)
    }
}

不明なタイプ(復号が必要な文字列にはどのフィールドがあるか分かりません)
Interfaceを使用してjsonを受信することができます.Unmarshalの結果は,type assertion特性(復号結果をmap[string]interface{}タイプに変換)を用いて後続動作を行う.
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)

    var f interface{}
    json.Unmarshal(b, &f)

    m := f.(map[string]interface{})
    fmt.Println(m["Parents"])  //    json   
    fmt.Println(m["a"] == nil) //        
}