【问题标题】:JSON Nested dynamic structures Go decodingJSON 嵌套动态结构 Go 解码
【发布时间】:2019-05-23 12:08:08
【问题描述】:

输入数据有一个例子。

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

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

【问题讨论】:

    标签: json go struct


    【解决方案1】:

    使用映射(map[string]SMSPhone 类型)在 JSON 中为 sms 对象建模:

    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)
    

    将导致(在Go Playground 上尝试):

    {Status:OK StatusCode:100 Sms:map[79035671233:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79105432212:{Status:ERROR StatusCode:203 StatusText:Нет текста сообщения} 79607891:{StatusERROR状态代码:203 状态文本:Нет текста сообщения}] 余额:2676.18}

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

    查看相关问题:

    How to parse/deserlize a dynamic JSON in Golang

    How to unmarshal JSON with unknown fieldnames to struct in golang?

    Unmarshal JSON with unknown fields

    Unmarshal json string to a struct that have one element of the struct itself

    【讨论】:

    • tnx 非常马赫,伙计。
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2021-08-21
    相关资源
    最近更新 更多