Home  >  Article  >  Backend Development  >  How to Unmarshal JSON with Varying Response Formats in Go?

How to Unmarshal JSON with Varying Response Formats in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 10:00:30662browse

How to Unmarshal JSON with Varying Response Formats in Go?

Unmarshalling JSON with Varying Response Formats in Go

When consuming external endpoints, you may encounter JSON responses with different formats. Handling these variations can be challenging, especially when you want to structure your response into a specific data type.

The Dilemma

You're facing an endpoint that returns JSON in two formats:

  • Format 1: { "message": "Message" }
  • Format 2: { "message": ["ERROR_CODE"] }

The challenge is to create a Go struct that can accommodate both response formats.

A Simple Approach

Initially, you considered using two separate structs, one for each format. However, this approach is not ideal as it requires multiple decoding attempts and error handling.

A More Elegant Solution

A more elegant solution involves unmarshalling the JSON into an interface{} type. Interface{} is a special type in Go that can hold any value, regardless of its specific type.

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

Once unmarshalled, you can use a type assertion or type switch to inspect the type of the Message field.

<code class="go">switch x := r.Message.(type) {
    case string:
        // Handle string message
    case []interface{}:
        // Handle array message
    default:
        // Handle unexpected type
}</code>

This approach allows you to handle both response formats within a single struct, providing a more robust and maintainable solution.

The above is the detailed content of How to Unmarshal JSON with Varying Response Formats in Go?. 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