"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Deserialize Dynamic Nested JSON Structures in Go?

How to Deserialize Dynamic Nested JSON Structures in Go?

Published on 2024-11-18
Browse:644

How to Deserialize Dynamic Nested JSON Structures in Go?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3