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} }
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 } }
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) }
In this code:
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!