Reputation: 712
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?
Upvotes: 1
Views: 563
Reputation: 417612
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
Upvotes: 5