Home > Backend Development > Golang > How to Handle JSON Unmarshalling When the Data Might Be an Array or an Object?

How to Handle JSON Unmarshalling When the Data Might Be an Array or an Object?

Susan Sarandon
Release: 2024-12-13 19:00:13
Original
394 people have browsed it

How to Handle JSON Unmarshalling When the Data Might Be an Array or an Object?

How to Unmarshall JSON with an Array or Object

When dealing with JSON, handling scenarios where the returned data may be an array or an object can be challenging. This article addresses the issue and presents a solution that involves using the json.RawMessage type and dynamic unmarshalling based on the JSON structure.

Unveiling the Dynamic JSON Structure

Consider the following JSON responses:

{"gwrcmds":{"gwrcmd":{"gcmd":"SPA_UserGetSmartMeterList","gdata":{"gip":{"version":"1"
Copy after login
{"gwrcmds":{"gwrcmd":[{"gcmd":"DeviceGetChart","gdata":{"gip":{"version":"1"
Copy after login

As seen from the responses, gwrcmd can either be an object or an array. To account for this, a custom Go struct is defined as:

type Response struct {
    Gwrcmds struct {
        Gwrcmd struct {
            Gcmd  string
            Gdata struct {
                Gip struct {
                    Version string
Copy after login

Solving the Unmarshalling Conundrum

The key to resolving this issue lies in utilizing json.RawMessage, which accepts any JSON value. We create a wrapper within the Response struct to hold the raw JSON:

type Response struct {
    RawAWrapper struct {
        RawA json.RawMessage `json:"a"`
    }
Copy after login

Dynamic Unmarshaling Based on JSON Structure

Within the UnmarshalJSON method of the Response struct, we examine the first byte of the RawAWrapper.RawA to determine if it represents an array or object. Depending on the result, we unmarshal the data accordingly:

func (r *Response) UnmarshalJSON(b []byte) error {
    if err := json.Unmarshal(b, &r.RawAWrapper); err != nil {
        return err
    }
    if r.RawAWrapper.RawA[0] == '[' {
        return json.Unmarshal(r.RawAWrapper.RawA, &r.As)
    }
    return json.Unmarshal(r.RawAWrapper.RawA, &r.A)
}
Copy after login

This approach provides flexibility in handling JSON with different structures without the need for multiple structs.

The above is the detailed content of How to Handle JSON Unmarshalling When the Data Might Be an Array or an Object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template