dongqian1925 2014-11-28 03:22
浏览 149
已采纳

如何用Go结构表示这种复杂的数据结构?

So I decided to give Go another chance but got stuck. Most Go struct examples in documentation are very simple and I found the following JSON object notation that I don't know how to represent with Go structs:

{
    id: 1,
    version: "1.0",
    method: "someString",
    params: [
        {
            clientid: "string",
            nickname: "string",
            level: "string"
        },
        [{
            value: "string",
            "function": "string"
        }]
    ]
}

How would you, more experienced gophers, represent that somewhat strange data in Go? And how to initialize the nested elements of the resulting struct?

  • 写回答

1条回答 默认 最新

  • doumouyi4039 2014-11-28 04:24
    关注

    I would use a json.RawMessage slice for the params property.. then hide them behind an GetXXX method that decodes it all nicely. Somewhat like this:

    type Outer struct {
        Id      int               `json:"id"`
        Version string            `json:"version"`
        Method  string            `json:"method"`
        Params  []json.RawMessage `json:"params"`
    }
    
    type Client struct {
        ClientId string `json:"clientid"`
        Nickname string `json:"nickname"`
        Level    string `json:"level"`
    }
    
    ....
    
    obj := Outer{}
    
    err := json.Unmarshal([]byte(js), &obj)
    
    if err != nil {
        fmt.Println(err)
    }
    
    fmt.Println(obj.Method) // prints "someString"
    
    client := Client{}
    
    err = json.Unmarshal(obj.Params[0], &client)
    
    fmt.Println(client.Nickname) // prints "string"
    

    Working (quickly smashed together at lunch time) sample: http://play.golang.org/p/Gp7UKj6pRK

    That second param will need some input from you .. but you're basically looking at decoding it to a slice of whatever type you create to represent it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址