golang JSON 编码解码总结

已知需要编码解码类型的

  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)
    }
}

结果

json.Marshal 编码结果:  {"name":"张三","age":24}
json.Unmarshal 解码结果:  李四 25
json.NewEncoder 编码结果: {"name":"王五","age":30}
json.NewDecoder 解码结果:  赵六 28

未知类型的(对于需要解码的字符串不知道具体有哪些字段)

我们可以使用 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) // 判断键是否存在
}
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!