Decoding Nested Dynamic Structures in JSON with Go
This article addresses the challenge of deserializing JSON data that features dynamic names within nested structures. Let's examine the problem and provide a solution.
Problem Statement
Consider the following JSON response:
{ "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 }
struct:
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 []SMSPhone `json:"sms"` Balance float64 `json:"balance"` }
The issue arises due to the dynamic phone numbers as property names within the "sms" object.
Solution
To handle this situation, we can utilize a map to represent 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"` }
Now, the deserialization code looks like this:
var result SMSSendJSON if err := json.Unmarshal([]byte(src), &result); err != nil { panic(err) }
This approach allows us to correctly process nested dynamic structures in Go.
The above is the detailed content of How to Deserialize JSON with Dynamic Names in Nested Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!