Type Assertions with Unmarshaled Data
In a distributed system, data is often exchanged as JSON strings. When retrieving JSON data from a message queue, you may encounter a scenario where you need to deserialize the data into an interface{} and then perform type assertions to determine the actual struct type of the data.
Problem
When unmarshaling the received JSON string into an interface{} and attempting to type assert the result, you may encounter an unexpected result. Instead of the expected struct type, you obtain a map[string]interface{}.
Solution
The default behavior of JSON unmarshaling into an interface{} yields types such as bool, float64, string, []interface{}, and map[string]interface{}. Since Something1 and Something2 are custom structs, they are not recognized by the JSON unmarshaler.
To resolve this, there are two main approaches:
1. Unmarshal Directly into Custom Structs
Code:
var input Something1 json.Unmarshal([]byte(msg), &input) // Type assertions and processing can be performed here var input Something2 json.Unmarshal([]byte(msg), &input) // Type assertions and processing can be performed here
2. Unpack from Map Interface
Code:
var input interface{} json.Unmarshal([]byte(msg), &input) // Unpack the data from the map switch v := input.(type) { case map[string]interface{}: // Extract the data from the map and assign it to custom structs }
Advanced Approach
For a more versatile solution, consider creating an "Unpacker" struct that handles the unmarshaling and type assertion process.
Code:
type Unpacker struct { Data interface{} } func (u *Unpacker) UnmarshalJSON(b []byte) error { smth1 := &Something1{} err := json.Unmarshal(b, smth1) if err == nil && smth1.Thing != "" { u.Data = smth1 return nil } smth2 := &Something2{} err = json.Unmarshal(b, smth2) if err != nil { return err } u.Data = smth2 return nil }
Conclusion
By using one of these approaches, you can successfully perform type assertions on data that is first unmarshaled into an interface{} from a JSON string. The choice of approach depends on the specific requirements of your application.
The above is the detailed content of How to Perform Type Assertions on Unmarshaled JSON Data in Go?. For more information, please follow other related articles on the PHP Chinese website!