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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With