Unmarshaling JSON to an Array of Objects in Go
Parsing JSON data into custom Go structs is essential for many programming tasks. This question explores how to parse JSON into an array of objects in Go.
The Problem
The JSON data provided in the question exhibits a specific format, where each key represents a unique identifier, and the corresponding value is a nested object containing several attributes. The goal is to unmarshal this JSON data into an array of structs, where each element in the array represents one of the nested objects in the JSON.
The code snippet provided in the question attempts to parse the JSON into a MonsterCollection struct, which contains a map of strings to Monster structs. However, the compiler reports an invalid operation error due to type mismatch.
The Solution
The main issue with the code snippet is that it unmarshals the JSON into an interface{} type, which allows for dynamic typing but has limited functionality. To access the specific fields within the nested objects, the v variable in the loop needs to be type-asserted to the correct type.
Additionally, the code attempts to insert the Monster objects into a map with integer keys. However, the Pool map is a map of strings to Monster structs, so the keys should be strings.
The following code demonstrates how to properly unmarshal the JSON into an array of Monster structs:
type Monster struct { MonsterId int32 `json:"monster-id"` Level int32 `json:"level"` SkillLevel int32 `json:"skill-level"` AimerId int32 `json:"aimer-id"` } type MonsterCollection struct { Pool map[string]Monster } func (mc *MonsterCollection) FromJson(jsonStr string) error { var data map[string]Monster b := []byte(jsonStr) err := json.Unmarshal(b, &data) if err != nil { return err } mc.Pool = data return nil }
In this code:
Now, the JSON data can be unmarshaled into the MonsterCollection struct and accessed through the Pool map, which provides a convenient way to retrieve individual monsters using their unique identifiers.
The above is the detailed content of How to Unmarshal JSON into an Array of Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!