我的websocket服务器将接收和解组JSON数据。此数据将始终包装在具有键/值对的对象中。密钥字符串将用作值标识符,告诉Go服务器它是哪种值。通过知道什么类型的值,然后我可以进行JSON解组值到正确的结构类型。
每个json对象可能包含多个键/值对。
JSON示例:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
有什么简单的方法可以使用"encoding/json"
软件包来做到这一点?
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)
}
感谢您的任何建议/帮助!
可以通过将其编组为map[string]json.RawMessage
。
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
要进一步解析sendMsg
,您可以执行以下操作:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
对于say
,您可以做同样的事情并解组为字符串:
var str string
err = json.Unmarshal(objmap["say"], &str)
编辑:请记住,您还需要导出sendMsg结构中的变量以正确解组。因此,您的结构定义将是:
type sendMsg struct {
User string
Msg string
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句