解组json数组到结构体 [英] Unmarshal json array to struct
问题描述
我有一组自定义值
I have an array of custom values
[
1,
"test",
{ "a" : "b" }
]
我可以解组到[] interface {},但它不是我想要的。
I can unmarshal in to []interface{}, but it's not what I want.
我想将这个数组解析为struct
I would like to unmarshal this array to struct
type MyType struct {
Count int
Name string
Relation map[string]string
}
是否可以在Go中使用标准或辅助库?
Is it possible in Go with standard or side libraries?
推荐答案
您可以使用 github.com/ugorji/go/codec ,它可以将数组解组成一个结构体:
You can use github.com/ugorji/go/codec, it can unmarshal array to a struct:
将一个结构体编码为一个数组,然后解码数据中的数组stream
Encode a struct as an array, and decode struct from an array in the data stream
尽管库提供了编码/ json的插入替换 - 它只是关于 json :
标签。所以你必须使用 codec.Decoder
而不是 json.Unmarshal
:
Although the library advertises "drop-in replacement for encoding/json" - it's only about the json:
tag. So you have to use codec.Decoder
instead of json.Unmarshal
:
package main
import "fmt"
import "github.com/ugorji/go/codec"
type MyType struct {
Count int
Name string
Relation map[string]string
}
func main() {
x := &MyType{}
data := []byte(`[1,"test",{"a":"b"}]`)
codec.NewDecoderBytes(data, new(codec.JsonHandle)).Decode(x)
fmt.Println(x)
}
这篇关于解组json数组到结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!