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"
{"gwrcmds":{"gwrcmd":[{"gcmd":"DeviceGetChart","gdata":{"gip":{"version":"1"
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
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"` }
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) }
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!