JSON嵌套动态结构进行解码 [英] JSON Nested dynamic structures Go decoding

查看:120
本文介绍了JSON嵌套动态结构进行解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入数据上有一个例子.

There is an example on the input data.

{
    "status": "OK",
    "status_code": 100,
    "sms": {
        "79607891234": {
            "status": "ERROR",
            "status_code": 203,
            "status_text": "Нет текста сообщения"
        },
        "79035671233": {
            "status": "ERROR",
            "status_code": 203,
            "status_text": "Нет текста сообщения"
        },
        "79105432212": {
            "status": "ERROR",
            "status_code": 203,
            "status_text": "Нет текста сообщения"
        }
    },
    "balance": 2676.18
}

type SMSPhone struct {
    Status     string `json:"status"`
    StatusCode int    `json:"status_code"`
    SmsID      string `json:"sms_id"`
    StatusText string `json:"status_text"`
}
type SMSSendJSON struct {
    Status     string     `json:"status"`
    StatusCode int        `json:"status_code"`
    Sms        []SMSPhone `json:"sms"`
    Balance    float64    `json:"balance"`
}

这是在向服务器发出适当请求后我收到的数据的示例.我得到了这样的数据.此类数据如何序列化?由于嵌套结构列表的动态名称,我的尝试失败了. 这样的嵌套动态结构如何正确处理?

This is an example of the data that I receive after the appropriate request to the server. And I get such data. How can such data be serialized? My attempt failed because of the dynamic names of the list of nested structures. How can such nested dynamic structures be correctly processed?

推荐答案

使用地图(类型为map[string]SMSPhone)对JSON中的sms对象建模:

Use a map (of type map[string]SMSPhone) to model the sms object in JSON:

type SMSPhone struct {
    Status     string `json:"status"`
    StatusCode int    `json:"status_code"`
    StatusText string `json:"status_text"`
}

type SMSSendJSON struct {
    Status     string              `json:"status"`
    StatusCode int                 `json:"status_code"`
    Sms        map[string]SMSPhone `json:"sms"`
    Balance    float64             `json:"balance"`
}

然后解封:

var result SMSSendJSON

if err := json.Unmarshal([]byte(src), &result); err != nil {
    panic(err)
}
fmt.Printf("%+v", result)

会产生结果(在进入游乐场上尝试):

Will result in (try it on the Go Playground):

{状态:正常状态代码:100 Sms:映射[79035671233:{状态:错误状态代码:203状态文本: StatusCode:203 StatusText:Неттекстасообщения}]余额:2676.18}

{Status:OK StatusCode:100 Sms:map[79035671233:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79105432212:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79607891234:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения}] Balance:2676.18}

result.Sms映射中的键是对象的动态"属性,即电话号码.

The keys in the result.Sms map are the "dynamic" properties of the object, namely the phone numbers.

查看相关问题:

如何解析/反动态化Golang中的JSON

如何解组

将未知字段的JSON封送

查看全文

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