当前位置:网站首页>Go语言JSON 处理

Go语言JSON 处理

2022-06-23 09:36:00 51CTO

JSON字符串解析到结构体

代码示例

      
      
type User struct {
Name string
FansCount int64
}

// 如果反序列化的时候指定明确的结构体和变量类型
func TestJsonUnmarshal(t *testing.T) {
const jsonStream = `
{"name":"ethancai", "fansCount": 9223372036854775807}
`
var user User // 类型为User
err := JsonUnmarshal(jsonStream, &user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v \n", user)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

解析Json数组到切片(数组)

      
      
type Person struct {
Name string
Age int
}

type Family struct {
Persons []Person
}

// 解析多维数组
var f Family

// 模拟传输的Json数据
familyJSON := `{"Persons": [{"Name":"Elinx","Age":26}, {"Name":"Twinkle","Age":21}] }`

fmt.Println("======================")

// 解析字符串为Json
json.Unmarshal([]byte(familyJSON), &f)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

运行结果

      
      
=== RUN TestJsonMash
======================
{[{Elinx 26 0001-01-01 00:00:00 +0000 UTC []} {Twinkle 21 0001-01-01 00:00:00 +0000 UTC []}]}
{"Persons":[{"Name":"Elinx","Age":26,"Birth":"0001-01-01T00:00:00Z","Children":null}
--- PASS: TestJsonMash (0.00s)
PASS
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

使用 struct tag 辅助构建 json

struct能被转换的字段都是首字母大写的字段,但如果想要在json中使用小写字母开头的key,可以使用struct的tag来辅助反射。

      
      
type Post struct {
Id int `json:"ID"`
Content string `json:"content"`
Author string `json:"author"`
Label []string `json:"label"`
}
func TestJsonMash1(t *testing.T){
postp := &Post{
2,
"Hello World",
"userB",
[]string{"linux", "shell"},
}

p, _ := json.MarshalIndent(postp, "", "\t")
fmt.Println(string(p))
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

运行结果:

      
      
=== RUN TestJsonMash1
{
"ID": 2,
"content": "Hello World",
"author": "userB",
"label": [
"linux",
"shell"
]
}
--- PASS: TestJsonMash1 (0.00s)
PASS
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

如何使用 tag

  • tag中标识的名称将称为json数据中key的值
  • tag可以设置为​​json:"-"​​来表示本字段不转换为json数据,即使这个字段名首字母大写
  • 如果想要json key的名称为字符"-",则可以特殊处理​​json:"-,"​​,也就是加上一个逗号
  • 如果tag中带有​​,omitempty​​选项,那么如果这个字段的值为0值,即false、0、""、nil等,这个字段将不会转换到json中
  • 如果字段的类型为bool、string、int类、float类,而tag中又带有​​,string​​选项,那么这个字段的值将转换成json字符串

解析 Json 数据到结构已知 struct

      
      
{
"id": 1,
"content": "hello world",
"author": {
"id": 2,
"name": "userA"
},
"published": true,
"label": [],
"nextPost": null,
"comments": [{
"id": 3,
"content": "good post1",
"author": "userB"
},
{
"id": 4,
"content": "good post2",
"author": "userC"
}
]
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

测试代码

      
      
type Post struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
Published bool `json:"published"`
Label []string `json:"label"`
NextPost *Post `json:"nextPost"`
Comments []*Comment `json:"comments"`
}

type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
}

type Comment struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}

func TestJsonStruct(t *testing.T){
jsonData :="{\n \"id\": 1,\n \"content\": \"hello world\",\n \"author\": {\n \"id\": 2,\n \"name\": \"userA\"\n },\n \"published\": true,\n \"label\": [],\n \"nextPost\": null,\n \"comments\": [{\n \"id\": 3,\n \"content\": \"good post1\",\n \"author\": \"userB\"\n },\n {\n \"id\": 4,\n \"content\": \"good post2\",\n \"author\": \"userC\"\n }\n ]\n}"
var post Post
// 解析json数据到post中
err := json.Unmarshal([]byte(jsonData), &post)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(post)
fmt.Println(post.Author, post.Content, post.Comments[0].Content,post.Comments[0].ID, post.Comments[0].Author )
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

运行结果

      
      
=== RUN TestJsonStruct
{1 hello world {2 userA} true [] < nil > [0xc00016d1a0 0xc00016d1d0]}
{2 userA} hello world good post1 3 userB
--- PASS: TestJsonStruct (0.00s)
PASS
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

获得更多内容,关注公众号程序员财富自由之路

Go语言JSON 处理_字段

公众号:程序员财富自由之路


关注我们,了解更多



原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_15683090/5410243