Go 使用 JSON

Encode

将一个对象编码成 JSON 数据,接受一个 interface{} 对象,返回 []byte 和 err

func Marshal(v interface{}) {[]byte,err}

Marshal 函数将会递归遍历整个对象,依次按照成员类型对这个对象进行编码,类型转换如下:

1 bool 类型转换成 JSON 的 boolean

2 整数、浮点数等数值类型转换成 JSON 的 Number

3 string 转换成 JSON 的字符串(带 "" 号)

4 struct 转换成 JSON 的 Object ,再根据各个成员的类型递归打包

5 数组或切片转换成 JSON 的 Array

6 []byte 会先进行 base64 编码然后转换成 JSON 字符串

7 map 转换成 JSON 的 Object ,key 必须是 string

8 interface{} 按照内部的实际类型进行转换

9 channel、func等类型,会返回 UnsupportedTypeError

如下示例:

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

// 定义一个结构体
type ColorGroup struct {
    ID int
    Name string
    Colors []string
}

func main() {
    group := ColorGroup{
        ID : 1,
        Name : "Reds",
        Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    }

    b,err := json.Marshal(group)
    if err != nil{
        fmt.Println("error:",err)
    }

    os.Stdout.Write(b)
}

----------------------------------------------------------------------------

输出结果:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

Decode

将 JSON 数据解码

func Unmarshal(data []byte,v interface{}) error

类型转换规则和上面的规则类似,如下示例:

package main

import (
    "encoding/json"
    "fmt"
)

// func UnMarshal(data []byte,v interface{}) error

type Animal struct {
    Name string
    Order string
}

func main() {
    var animals []Animal
    jsonBlob := `[
         {"Name" : "Platypus","Order" : "Monotremata"},
         {"Name": "Quoll",    "Order": "Dasyuromorphia"}
    ]`

    err := json.Unmarshal([]byte(jsonBlob),&animals)
    if err != nil {
        fmt.Println("error:",err)
    }

    fmt.Println(animals)
}

------------------------------------------------------------------

输出结果:

[{Platypus Monotremata} {Quoll Dasyuromorphia}]

评论

暂无评论