Go中的自定义JSON映射功能 [英] Custom JSON mapping function in Go

查看:130
本文介绍了Go中的自定义JSON映射功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在制作一个Go服务,该服务调用了一个宁静的API,但我无法控制正在调用的API.

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.

我知道Go在NewDecoder-> Decode中有一个不错的内置反序列化器,但是它仅适用于以大写字母开头的结构域(又称公共域).这引起了一个问题,因为我要使用的JSON看起来像这样:

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

我将如何映射"_next"?

推荐答案

使用

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"`
}

测试:

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"
}`

输出(在游乐场上尝试):

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

还请注意,您也可以解组映射或interface{}值,因此您甚至不必创建结构,但是使用它并不像结构那样方便:

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"
}`

输出(在游乐场上尝试):

map[_next:someValue data:[one 2] message:success]

这篇关于Go中的自定义JSON映射功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆