Home  >  Article  >  Backend Development  >  How to Elegantly Handle JSON Responses with Varying Formats?

How to Elegantly Handle JSON Responses with Varying Formats?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 10:42:03627browse

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>

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

Success, message: Message
Error, code: [ERROR_CODE]

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!

Statement:
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