在 Go 中部分 JSON 解组为地图 [英] Partly JSON unmarshal into a map in Go
问题描述
我的 websocket 服务器将接收和解组 JSON 数据.此数据将始终包含在具有键/值对的对象中.key-string 将作为值标识符,告诉 Go 服务器它是什么类型的值.通过知道什么类型的值,我可以继续使用 JSON 将值解组为正确的结构类型.
My websocket server will receive and unmarshal JSON data. This data will always be wrapped in an object with key/value pairs. The key-string will act as value identifier, telling the Go server what kind of value it is. By knowing what type of value, I can then proceed to JSON unmarshal the value into the correct type of struct.
每个 json-object 可能包含多个键/值对.
Each json-object might contain multiple key/value pairs.
示例 JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
有没有什么简单的方法可以使用 "encoding/json"
包来做到这一点?
Is there any easy way using the "encoding/json"
package to do this?
package main
import (
"encoding/json"
"fmt"
)
// the struct for the value of a "sendMsg"-command
type sendMsg struct {
user string
msg string
}
// The type for the value of a "say"-command
type say string
func main(){
data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)
// This won't work because json.MapObject([]byte) doesn't exist
objmap, err := json.MapObject(data)
// This is what I wish the objmap to contain
//var objmap = map[string][]byte {
// "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
// "say": []byte(`"hello"`),
//}
fmt.Printf("%v", objmap)
}
感谢您的任何建议/帮助!
Thanks for any kind of suggestion/help!
推荐答案
这可以通过解组为 map[string]json.RawMessage
来实现.
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
要进一步解析sendMsg
,您可以执行以下操作:
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
对于say
,你可以做同样的事情并解组成一个字符串:
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
<小时>
请记住,您还需要导出 sendMsg 结构中的变量以正确解组.所以你的结构定义是:
Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
示例:https://play.golang.org/p/OrIjvqIsi4-
这篇关于在 Go 中部分 JSON 解组为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!