Decoding JSON with Variant Structures
The endpoint you're consuming returns JSON in varying formats, sometimes as a string and other times as an array. To handle this inconsistency, the following question explores the best approach to designing a Go struct that can accommodate both types.
The Question:
How can I create a Go struct that can unmarshal JSON data with variable types, either a string or an array of strings? Is there an elegant solution beyond attempting to decode into two separate structs?
The Answer:
A more sophisticated approach involves unmarshaling the JSON into an interface{} type. This type-agnostic approach allows for dynamic handling of different value types.
To implement this technique, create a struct with a field of type interface{}, as demonstrated in the following example:
<code class="go">type Response struct { Message interface{} `json:"message"` }</code>
When unmarshaling the JSON data into this struct, you can use a type switch or type assertion to determine the actual type of the Message field. This allows you to process the data accordingly.
Here's an example implementation:
<code class="go">func main() { inputs := []string{ `{"message":"Message"}`, `{"message":["ERROR_CODE"]}`, } for _, input := range inputs { var r Response if err := json.Unmarshal([]byte(input), &r); err != nil { panic(err) } switch x := r.Message.(type) { case string: fmt.Println("Success, message:", x) case []interface{}: fmt.Println("Error, code:", x) default: fmt.Println("Something else:", x) } } }</code>
Output:
Success, message: Message Error, code: [ERROR_CODE]
By utilizing the interface{} approach, you gain flexibility in handling JSON data with varying types, simplifying your codebase.
The above is the detailed content of How to Unmarshal JSON Data with Variable Types: String or Array of Strings?. For more information, please follow other related articles on the PHP Chinese website!