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条)

报告相同问题?