如何将JSON解组到J中的接口{}中? [英] How to unmarshal JSON into interface{} in Go?
问题描述
type消息struct {
Cmd string`json :cmd`
数据接口{}`json:data`
}
我也有一个类型叫做CreateMessage,就像这样:
pre codereate $ ] int`json:conf`
Info map [string] int`json:info`
}
我有一个JSON字符串,如 {cmd:create,data:{conf:{a:1},信息 :{ b:2}}}
。
当我使用 json.Unmarshal
将其解码为Message变量时,答案是 {Cmd:create Data:map [conf:map [a:1] info:map [b:2]]}
。
那么我可以将JSON解码为Message结构并根据Cmd改变它的Data的接口来输入CreateMessage?我试图直接将Data转换为类型CreateMessage,但是编译器告诉我Data是一个map [sting] interface {}类型。解析方案
通过 json.RawMessage 字段捕获消息的变体部分。
type消息struct {
cmd字符串`json:cmd`
数据json.RawMessage
}
类型CreateMessage结构体{
Conf map [string] int`json:conf `
Info map [string] int`json:info`
}
func main(){
var m消息
if err := json.Unmarshal(data,& m); err!= nil {
log.Fatal(err)
}
switch m.Cmd {
casecreate:
var cm CreateMessage
if err:= json.Unmarshal([] byte(m.Data),& cm); err!= nil {
log.Fatal(err)
}
fmt.Println(m.Cmd,cm.Conf,cm.Info)
默认值:
log.Fatal(bad command)
}
}
I'm a newbie in Go and now I have a problem. I have a type called Message, it is a struct like this:
type Message struct {
Cmd string `json:"cmd"`
Data interface{} `json:"data"`
}
I also have a type called CreateMessage like this:
type CreateMessage struct {
Conf map[string]int `json:"conf"`
Info map[string]int `json:"info"`
}
And I have a JSON string like {"cmd":"create","data":{"conf":{"a":1},"info":{"b":2}}}
.
When I use json.Unmarshal
to decode that into a Message variable, the answer is {Cmd:create Data:map[conf:map[a:1] info:map[b:2]]}
.
So could I decode the JSON into a Message struct and change its Data's interface{} to type CreateMessage according to the Cmd?
I tried to convert Data directly into type CreateMessage but the complier told me that Data is a map[sting]interface{} type.
Define a struct type for the fixed part of the message with a json.RawMessage field to capture the variant part of the message. Define struct types for each of the variant types and decode to them based on the the command.
type Message struct {
Cmd string `json:"cmd"`
Data json.RawMessage
}
type CreateMessage struct {
Conf map[string]int `json:"conf"`
Info map[string]int `json:"info"`
}
func main() {
var m Message
if err := json.Unmarshal(data, &m); err != nil {
log.Fatal(err)
}
switch m.Cmd {
case "create":
var cm CreateMessage
if err := json.Unmarshal([]byte(m.Data), &cm); err != nil {
log.Fatal(err)
}
fmt.Println(m.Cmd, cm.Conf, cm.Info)
default:
log.Fatal("bad command")
}
}
这篇关于如何将JSON解组到J中的接口{}中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!