dougu2036 2017-03-27 15:16
浏览 40
已采纳

Go中的自定义JSON映射功能

So I'm making a Go service that makes a call to a restful API, I have no control over the API I'm calling.

I know that Go has a nice built in deserializer in NewDecoder->Decode, but it only works for struct fields that start with capital letters (aka public fields). Which poses a problem because the JSON I'm trying to consume looks like this:

{
    "_next": "someValue",
    "data":  [{/*a collection of objects*/}],
    "message": "success"
}

How the heck would I map "_next"?

  • 写回答

2条回答 默认 最新

  • duanchun2349 2017-03-27 15:22
    关注

    Use tags to specify the field name in JSON. The JSON object you posted above can be modeled like this:

    type Something struct {
        Next    string        `json:"_next"`
        Data    []interface{} `json:"data"`
        Message string        `json:"message"`
    }
    

    Testing it:

    func main() {
        var sg Something
        if err := json.Unmarshal([]byte(s), &sg); err != nil {
            panic(err)
        }
        fmt.Printf("%+v", sg)
    }
    
    const s = `{
        "_next": "someValue",
        "data":  ["one", 2],
        "message": "success"
    }`
    

    Output (try it on the Go Playground):

    {Next:someValue Data:[one 2] Message:success}
    

    Also note that you may also unmarshal into maps or interface{} values, so you don't even have to create structs, but it won't be as convenient using it as the structs:

    func main() {
        var m map[string]interface{}
        if err := json.Unmarshal([]byte(s), &m); err != nil {
            panic(err)
        }
        fmt.Printf("%+v", m)
    }
    
    const s = `{
        "_next": "someValue",
        "data":  ["one", 2],
        "message": "success"
    }`
    

    Output (try it on the Go Playground):

    map[_next:someValue data:[one 2] message:success]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错