Home > Backend Development > Golang > How to Safely Unmarshal JSON into an Interface{} and Handle Type Assertion?

How to Safely Unmarshal JSON into an Interface{} and Handle Type Assertion?

Linda Hamilton
Release: 2024-12-17 11:59:25
Original
558 people have browsed it

How to Safely Unmarshal JSON into an Interface{} and Handle Type Assertion?

Unmarshaling into an Interface{} and Performing Type Assertion

Unmarshaling JSON into an interface{} allows for handling a diverse range of data types. However, directly asserting the type of the unmarshaled interface{} poses challenges.

In the given scenario, the interface{} is unmarshaled from a received message. Attempting to perform a type switch on this interface{} as seen in the code snippet produces unexpected results, with the type being declared as map[string]interface{}.

To resolve this issue, it's important to understand the default types that the JSON package unmarshals into, as listed in its documentation:

  • bool
  • float64
  • string
  • []interface{}
  • map[string]interface{}
  • nil

Since the unmarshaling is performed into an interface{}, the resulting type will be limited to this set. Therefore, the package is unaware of custom structs like Something1 and Something2.

Solution Options:

1. Direct Unmarshaling:

To avoid intermediate interface{} handling, JSON data can be directly unmarshaled into the desired struct type. For instance:

var job Something1
json.Unmarshal([]byte(msg), &job)
Copy after login

2. Convert from Generic Interface:

If working with a generic interface{} is necessary, the data can be manually unpacked from the map[string]interface{}. Here's an example:

var input interface{}
json.Unmarshal([]byte(msg), &input)

if smth1, ok := input.(map[string]interface{}); ok {
  job := Something1{
    Thing:        smth1["thing"].(string),
    OtherThing:   smth1["other_thing"].(int64),
  }
}
Copy after login

3. Wrapper Struct:

For cases where handling various data types is common, a wrapper struct with a custom UnmarshalJSON method can simplify the process. This method can attempt to unmarshal the data into different structs and set the Data field accordingly.

The above is the detailed content of How to Safely Unmarshal JSON into an Interface{} and Handle Type Assertion?. 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