go struct 与 json

栏目: Go · 发布时间: 7年前

内容简介:使用marshal方法进行编码。

go struct 与 json

https://golang.org/pkg/encoding/json/#pkg-index

成员标签-tag

https://sosedoff.com/2016/07/16/golang-struct-tags.html

Only data structures that can be represented as valid JSON will be encoded:

JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).
// JSON的key只能是string类型,所有在支持Map的情况下,需要其对应的Map的key是string类型。

Channel, complex, and function types cannot be encoded.
// 这些类型是无法被encoded的

Cyclic data structures are not supported; they will cause Marshal to go into an infinite loop.
// 循环数据类型无法被encoded

Pointers will be encoded as the values they point to (or 'null' if the pointer is nil).
// 指针类型可以被encoded
The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.
// 只能访问那些exported的struct types类型的field(大写字母开头的)

使用

encode

使用marshal方法进行编码。

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

举例使用一个 go 定义的一个structure Message

type Message struct {
    Name string
    Body string
    Time int64
}

使用一个Message的实例被编码完以后的结果类似于下面

b == []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)

编码中需要注意的内容

Only data structures that can be represented as valid JSON will be encoded:

JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).

// JSON的key只能是string类型,所有在支持Map的情况下,需要其对应的Map的key是string类型。

Channel, complex, and function types cannot be encoded.

// 这些类型是无法被encoded的

Cyclic data structures are not supported; they will cause Marshal to go into an infinite loop.

// 循环数据类型无法被encoded

Pointers will be encoded as the values they point to (or 'null' if the pointer is nil).

// 指针类型可以被encoded

The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.

// 只能访问那些exported的struct types类型的field(大写字母开头的)

decode

https://blog.golang.org/json-and-go


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

挑战程序设计竞赛

挑战程序设计竞赛

秋叶拓哉、岩田阳一、北川宜稔 / 巫泽俊、庄俊元、李津羽 / 人民邮电出版社 / 2013-7-1 / CNY 79.00

世界顶级程序设计高手的经验总结 【ACM-ICPC全球总冠军】巫泽俊主译 日本ACM-ICPC参赛者人手一册 本书对程序设计竞赛中的基础算法和经典问题进行了汇总,分为准备篇、初级篇、中级篇与高级篇4章。作者结合自己丰富的参赛经验,对严格筛选的110 多道各类试题进行了由浅入深、由易及难的细致讲解,并介绍了许多实用技巧。每章后附有习题,供读者练习,巩固所学。 本书适合程序设计......一起来看看 《挑战程序设计竞赛》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具