douzhang6496 2014-06-11 16:44
浏览 48
已采纳

如何为Go结构创建JSON

I am trying to use the Marshal function to create JSON from a Go struct. The JSON created does not contain the Person struct.
What am I missing?

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.
http://golang.org/pkg/encoding/json/#Marshal

  • 写回答

1条回答 默认 最新

  • drmticpet66231422 2014-06-11 16:47
    关注

    You are missing two things.

    1. Only Public fields can be Marshaled to json.
    2. The name written to json is the name of the fieldd. In this case P for the field 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. Is common to tag most of the fields and change the name to lowercase to be in sync with javascript's style.

    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"}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行