Handling Multiple JSON Formats with Unmarshaling in Go
When consuming a third-party API that returns JSON in different formats, it can be challenging to handle the varying structures in Go. One common challenge is dealing with responses that can contain either a string or an array in a "message" field.
A Simple Approach
A basic approach would involve creating separate structs for each format:
<code class="go">type ResponseWithString struct { Message string `json:"message"` } type ResponseWithArray struct { Message []string `json:"message"` }</code>
You can then attempt to decode the JSON into both structs in succession. If the first attempt (with string) fails, you would try the second attempt (with array).
A More Elegant Solution
A more elegant approach is to use the interface{} type, which can hold any type of value. By unmarshalling the JSON into a variable of type interface{}, you can dynamically check its type and respond accordingly.
<code class="go">type Response struct { Message interface{} `json:"message"` } func main() { ... var r Response ... switch x := r.Message.(type) { case string: // Handle string message case []interface{}: // Handle array message } }</code>
Note that by default, JSON arrays are unmarshalled into []interface{}, so you can use type assertions to distinguish between a string and an array.
This approach provides greater flexibility and code reusability, as you can handle multiple JSON formats with a single struct.
The above is the detailed content of How Do You Handle Multiple JSON Formats in Go When Unmarshaling?. For more information, please follow other related articles on the PHP Chinese website!