Home > Backend Development > Golang > How to Handle Type Assertion After Unmarshaling JSON into an `interface{}` in Go?

How to Handle Type Assertion After Unmarshaling JSON into an `interface{}` in Go?

DDD
Release: 2024-12-16 21:29:19
Original
611 people have browsed it

How to Handle Type Assertion After Unmarshaling JSON into an `interface{}` in Go?

Unmarshaling into an Interface{} and Performing Type Assertion

When receiving messages through a RabbitMQ system and performing type assertion, it's important to understand the types that are unmarshaled by the json package.

Default Unmarshaling Types

By default, json.Unmarshal returns values of the following types:

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

Unmarshaling into an Interface{}

When unmarshaling into an interface{}, the returned value will be a generic map[string]interface{}. To determine the actual type within the map, you can either:

  • Unpack the data manually from the map.
  • Unmarshal directly into the desired struct type.

Example Using a Wrapper Struct

To avoid manually unpacking data, consider using a wrapper struct like the following:

This wrapper struct allows you to unmarshal data into either Something1 or Something2, depending on the type of data received.

The above is the detailed content of How to Handle Type Assertion After Unmarshaling JSON into an `interface{}` in Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template