Custom JSON mapping function in Go

大兔子大兔子 提交于 2019-12-20 03:13:13

问题


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"?


回答1:


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]



回答2:


Tags will solve your problem.

Hoping it may help others who come here, you can make use of https://mholt.github.io/json-to-go/ to generate Go structs. Paste a JSON structure on the left and the equivalent Go type will be generated to the right, which you can paste into your program.



来源:https://stackoverflow.com/questions/43050246/custom-json-mapping-function-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!