简体   繁体   中英

JSON Nested dynamic structures Go decoding

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?

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

Then unmarshaling:

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

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

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

See related questions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM