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

How to Efficiently Unmarshal JSON into an Array of Go Structs?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 10:11:14719browse

How to Efficiently Unmarshal JSON into an Array of Go Structs?

Unmarshalling JSON into an Array of Objects in Go

You encounter a challenge while attempting to parse a JSON object into an array of custom structs. The JSON you provided, however, appears to be invalid as it lacks commas between key-value pairs in the top-level object. Here's the corrected and formatted JSON:

{
   "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
   }
}

Parsing with Type Assertions

Your initial attempt to parse the JSON encountered an error because you assigned the map resulting from JSON unmarshalling to an interface{} value. When indexing this map, you need to type assert the value again with v.(map[string]interface{}) and each time you retrieve a key from the map.

Additionally, you attempted to insert an int as the key of a map with strings as keys, which would result in a further error.

Efficient Unmarshalling

To simplify the unmarshalling process and avoid manual type assertions, you can use a technique where you provide unmarshalling with the target data type directly. Here's an updated example:

package main

import (
    "encoding/json"
)

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)
}

func main() {
    jsonString := `{
        "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
        }
    }`

    mc := MonsterCollection{}
    if err := mc.FromJson(jsonString); err != nil {
        // Handle error
    }

    for _, monster := range mc.Pool {
        // Access monster data here
    }
}

The above is the detailed content of How to Efficiently Unmarshal JSON into an Array of Go Structs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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