Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshal json array to struct

Tags:

json

go

I have an array of custom values

[
    1,
    "test",
    { "a" : "b" }
]

I can unmarshal in to []interface{}, but it's not what I want.

I would like to unmarshal this array to struct

type MyType struct {
    Count int
    Name string
    Relation map[string]string
}

Is it possible in Go with standard or side libraries?

like image 734
Alexander Ponomarev Avatar asked Mar 20 '14 09:03

Alexander Ponomarev


1 Answers

The other answers seem too complicated, here is another approach:

package main

import (
   "encoding/json"
   "fmt"
)

type myType struct {
   count int
   name string
   relation map[string]string
}

func (t *myType) UnmarshalJSON(b []byte) error {
   a := []interface{}{&t.count, &t.name, &t.relation}
   return json.Unmarshal(b, &a)
}

func main() {
   var t myType
   json.Unmarshal([]byte(`[1, "test", {"a": "b"}]`), &t)
   fmt.Printf("%+v\n", t)
}

https://eagain.net/articles/go-json-array-to-struct

like image 198
Zombo Avatar answered Oct 26 '22 20:10

Zombo