简体   繁体   English

如何为Go结构创建JSON

[英]How to create JSON for Go struct

I am trying to use the Marshal function to create JSON from a Go struct. 我正在尝试使用Marshal函数从Go结构创建JSON。 The JSON created does not contain the Person struct. 创建的JSON不包含Person结构。
What am I missing? 我错过了什么?

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

type Person struct {
    fn string
    ln string
}
type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
    P      Person
}

per := Person{
    fn: "John",
    ln: "Doe",
}

group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    P:      per,
}
b, err := json.Marshal(group)
if err != nil {
    fmt.Println("error:", err)
}
os.Stdout.Write(b)

The output generated is as follows: 生成的输出如下:

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"],"P":{}}

I don't see Person in the output. 我没有在输出中看到Person。
http://golang.org/pkg/encoding/json/#Marshal http://golang.org/pkg/encoding/json/#Marshal

You are missing two things. 你错过了两件事。

  1. Only Public fields can be Marshaled to json. 只有公共字段可以被封送到json。
  2. The name written to json is the name of the fieldd. 写入json的名称是fieldd的名称。 In this case P for the field Person. 在这种情况下P为字段Person。

Notice that I changed the Fields name to be capital for the Person struct and that I added a tag json on the ColorGroup Struct to indicate that I want that field to be serialized with another name. 请注意,我将Fields名称更改为Person结构的大写,并且我在ColorGroup Struct上添加了一个tag json,以指示我希望该字段使用其他名称进行序列化。 Is common to tag most of the fields and change the name to lowercase to be in sync with javascript's style. 通常标记大多数字段并将名称更改为小写以与javascript的样式同步。

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

package main

import (
"encoding/json"
"fmt"
"os"
)

func main() {
type Person struct {
    Fn string
    Ln string
}
type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
    P Person `json:"Person"`
}

per := Person{Fn: "John",
            Ln: "Doe",
    }

group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    P: per,
}
b, err := json.Marshal(group)
if err != nil {
    fmt.Println("error:", err)
}
os.Stdout.Write(b)
}

Will output 会输出

{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"],"Person":{"Fn":"John","Ln":"Doe"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM