在Go中编码嵌套的JSON

pra*_*ram 3 encoding serialization json go

找到一个这样的例子我遇到了很多麻烦.互联网上的大多数信息都是关于解码JSON的.

我想将一些数据序列化为嵌套的JSON,例如:

{
  "item": {
      "title": "Items",
    "properties": [
      {
        "num": 1,
        "name": "Item 1"
      },
      {
        "num": 2,
        "name": "Item 2"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道如何使用平面结构编组数据,但是如何将数据放入可以使用嵌套序列化的结构中?

http://play.golang.org/p/nDKmv1myTD

我发现这个工具从JSON模式生成结构,但我不明白如何将数据导入子结构.

http://mholt.github.io/json-to-go/

type Example struct {
    Item struct {
        Title string `json:"title"`
        Properties []struct {
            Num int `json:"num"`
            Name string `json:"name"`
        } `json:"properties"`
    } `json:"item"`
}
Run Code Online (Sandbox Code Playgroud)

cre*_*ack 10

你找到的这个工具很好,但我不会用它.这使得初始化结构变得困难.

您的代码段的Init示例:(http://play.golang.org/p/_Qw3Qp8XZh)

package main

import (
    "encoding/json"
    "fmt"
)

type Example struct {
    Item struct {
        Title      string `json:"title"`
        Properties []struct {
            Num  int    `json:"num"`
            Name string `json:"name"`
        } `json:"properties"`
    } `json:"item"`
}

func main() {
    info := &Example{
        Item: struct {
            Title      string `json:"title"`
            Properties []struct {
                Num  int    `json:"num"`
                Name string `json:"name"`
            } `json:"properties"`
        }{
            Title: "title",
            Properties: []struct {
                Num  int    `json:"num"`
                Name string `json:"name"`
            }{
                {Num: 0, Name: "name0"},
                {Num: 1, Name: "name1"},
            },
        },
    }

    b, err := json.Marshal(info)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}
Run Code Online (Sandbox Code Playgroud)

结果(漂亮印刷):

{
  "item": {
    "title": "title",
    "properties": [
      {
        "num": 0,
        "name": "name0"
      },
      {
        "num": 1,
        "name": "name1"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为使用命名结构与匿名嵌套结构更好.

命名结构的相同示例:http://play.golang.org/p/xm7BXxEGTC

package main

import (
    "encoding/json"
    "fmt"
)

type Example struct {
    Item Item `json:"item"`
}

type Item struct {
    Title      string     `json:"title"`
    Properties []Property `json:"properties"`
}

type Property struct {
    Num  int    `json:"num"`
    Name string `json:"name"`
}

func main() {
    info := &Example{
        Item: Item{
            Title: "title",
            Properties: []Property{
                {Num: 0, Name: "name0"},
                {Num: 1, Name: "name1"},
            },
        },
    }

    b, err := json.Marshal(info)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}
Run Code Online (Sandbox Code Playgroud)

这是完全相同的事情,但我发现它更清晰易用.