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

How to Unmarshal a JSON Object into an Array of Structs in Go?

Barbara Streisand
Release: 2024-11-29 13:26:19
Original
264 people have browsed it

How to Unmarshal a JSON Object into an Array of Structs in Go?

How to Unmarshal JSON to Array of Objects in Go

Question

How can I unmarshal the following JSON into an array of objects in the Go language?

{
    "1001": {"level":10, "monster-id": 1001, "skill-level": 1, "aimer-id": 301},
    "1002": {"level":12, "monster-id": 1002, "skill-level": 1, "aimer-id": 302},
    "1003": {"level":16, "monster-id": 1003, "skill-level": 2, "aimer-id": 303}
}
Copy after login

Solution

The provided JSON requires some modifications to be valid, such as adding commas between key-value pairs in the top-level object:

{
   "1001":{
      "level":10,
      "monster-id":1001,
      "skill-level":1,
      "aimer-id":301
   },
   "1002":{
      "level":12,
      "monster-id":1002,
      "skill-level":1,
      "aimer-id":302
   },
   "1003":{
      "level":16,
      "monster-id":1003,
      "skill-level":2,
      "aimer-id":303
   }
}
Copy after login

To unmarshal this JSON into an array of objects, you can use the following code:

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 =&mc.Pool
    b := []byte(jsonStr)
    return json.Unmarshal(b, data)
}
Copy after login

In this code:

  • The Monster struct represents the structure of the objects.
  • The MonsterCollection struct contains a pool of monsters, each keyed by a string.
  • The FromJson method unmarshals the JSON string into the Pool map.

The error return is useful for debugging purposes, allowing you to detect errors such as invalid JSON syntax.

A working example can be found on the Golang Playground: http://play.golang.org/p/4EaasS2VLL.

The above is the detailed content of How to Unmarshal a JSON Object into an Array of Structs 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