Decoding Nested Dynamic JSON Structures in Go
In Go, deserializing JSON data with nested dynamic structures can be challenging. A recent query illustrates this issue:
{ "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 }
To deserialize such data, we need to use a map to model the dynamic list of SMS statuses. Here's the modified code:
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"` }
Now, Unmarshaling the JSON data with this modified struct:
var result SMSSendJSON if err := json.Unmarshal([]byte(src), &result); err != nil { panic(err) } fmt.Printf("%+v", result)
Will correctly deserialize the dynamic nested structures, resulting in:
{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 correspond to the dynamic phone numbers, and their values are the respective SMS statuses.
The above is the detailed content of How to Deserialize Dynamic Nested JSON Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!