Go 语言编程 — encoding/json 库

目录

encoding/json

Golang 提供了的标准库 encoding/json 对 JSON 数据进行编解码,并且允许使用 map[string]interface{}[]interface{} 类型的值来分别存放未知结构的 JSON 对象或数组。

使用 json.Marshal() 函数对一组数据进行 JSON 格式的编码

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

示例:

type Book struct { 
    Title string
    Authors []string 
    Publisher string 
    IsPublished bool 
    Price float
}


gobook := Book{
    "Go 语言编程",
    ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"],
    "xxx.com.cn",
    true,
    9.99
}


b, err := json.Marshal(gobook)


b == []byte(`{
    "Title": "Go语言编程",
    "Authors": ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"],
    "Publisher": "xxx.com.cn",
    "IsPublished": true,
    "Price": 9.99
}`)

编码时的数据类型映射如下:

  • 布尔值:转化为 JSON 后还是布尔类型。
  • 浮点数和整型:转化为 JSON 里边的常规数字。
  • 字符串:以 UTF-8 编码转化输出为 Unicode 字符集的字符串,特殊字符比如 “<” 将会被转义为 \u003c。
  • 数组和切片:转化为 JSON 里边的数组,但 []byte 类型的值将会被转化为 Base64 编码后的字符串,Slice 类型的零值会被转化为 null。
  • 结构体:转化为 JSON 对象,并且只有结构体里边以大写字母开头的可被导出的字段才会被转化输出,而这些可导出的字段会作为 JSON 对象的字符串索引。

注意,转化一个 Map 类型的数据结构时,该数据的类型必须是 map[string]T(T 可以是 encoding/json 包支持的任意数据类型)。

使用 json.Unmarshal() 函数对 JSON 数据进行解码

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

解码时的数据类型映射

  • JSON 中的布尔值:转换为 Go 中的 Bool 类型。
  • JSON 中的数值:转换为 Go 中的 Float64 类型。
  • JSON 中的字符串:转换为 Go 中的 String 类型。
  • JSON 中的数组:转换为 Go 中的 []interface{} 类型。
  • JSON 中的对象(Object):转换为 Go 中的 map[string]interface{} 类型。
  • JSON 中的 null 值:转换为 Go 中的 nil。

猜你喜欢

转载自blog.csdn.net/Jmilk/article/details/108293351