Home > Backend Development > Golang > How to Unmarshal JSON into an Array of Objects in Go?

How to Unmarshal JSON into an Array of Objects in Go?

Mary-Kate Olsen
Release: 2024-11-27 08:19:09
Original
222 people have browsed it

How to Unmarshal JSON into an Array of Objects in Go?

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
}
Copy after login

In this code:

  • The Monster struct uses json tags to map the field names to the corresponding JSON keys.
  • The MonsterCollection struct contains a map of strings to Monster structs, using the unique identifiers as keys.
  • The FromJson method of MonsterCollection takes the JSON string as an argument, unmarshals it into the data map, assigns the map to the Pool field, and returns any errors encountered.

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!

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