前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言JSON 处理

Go语言JSON 处理

作者头像
王小明_HIT
发布2021-10-11 17:06:29
8250
发布2021-10-11 17:06:29
举报
文章被收录于专栏:程序员奇点程序员奇点

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

解析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)

运行结果

=== 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
使用 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))
}

运行结果:

=== RUN   TestJsonMash1
{
 "ID": 2,
 "content": "Hello World",
 "author": "userB",
 "label": [
  "linux",
  "shell"
 ]
}
--- PASS: TestJsonMash1 (0.00s)
PASS
如何使用 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"
        }
    ]
}

测试代码

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

运行结果

=== RUN   TestJsonStruct
{1 hello world {2 userA} true [] <nil> [0xc00016d1a0 0xc00016d1d0]}
{2 userA} hello world good post1 3 userB
--- PASS: TestJsonStruct (0.00s)
PASS
参考资料
  • https://www.cnblogs.com/f-ck-need-u/p/10080793.html
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-09-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员奇点 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • JSON字符串解析到结构体
    • 代码示例
    • 解析Json数组到切片(数组)
      • 使用 struct tag 辅助构建 json
        • 如何使用 tag
          • 解析 Json 数据到结构已知 struct
            • 参考资料
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档