How to Elegantly Handle JSON Responses with Varying Formats?

Barbara Streisand
Release: 2024-10-27 10:42:03
Original
627 people have browsed it

How to Elegantly Handle JSON Responses with Varying Formats?

Exploring Approaches for Handling JSON Responses with Varying Formats

In scenario where a consumed endpoint returns JSON in diverse formats, it's crucial to find an elegant approach for handling these variations. The dilemma arises due to the endpoint's immutable nature.

A common strategy involves using multiple structs for decoding, attempting to decode into a struct expecting a string and switching to an alternate struct with an array upon encountering an error. While this method achieves the desired functionality, there may be a more refined approach.

Utilizing Type Assertions and Type Switches

A recommended solution is to unmarshal the JSON into an interface{} value. This value can then be examined using type assertions or type switches to determine its actual type.

An example in Go demonstrates the effectiveness of this approach:

<code class="go">type Response struct {
    Message interface{} `json:"message"`
}

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>
Copy after login

The output showcases the successful handling and distinction of the JSON response formats:

Success, message: Message
Error, code: [ERROR_CODE]
Copy after login

By leveraging this approach, you can handle different JSON formats with ease, eliminating the need for multiple structs or error handling.

The above is the detailed content of How to Elegantly Handle JSON Responses with Varying Formats?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!