我的websocket服务器将接收和解组JSON数据.此数据将始终包含在具有键/值对的对象中.密钥字符串将充当值标识符,告诉Go服务器它是什么类型的值.通过知道什么类型的值,我可以继续JSON将值解组为正确的结构类型.
每个json对象可能包含多个键/值对.
示例JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法使用"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 …Run Code Online (Sandbox Code Playgroud) 我想创建一个可以转换为json对象的地图,例如
{
"a": "apple",
"b": 2
}
Run Code Online (Sandbox Code Playgroud)
但是golang指定地图是用类型声明的,所以我可以有map [string] string或map [string] int.如何像上面那样创建一个json对象?
注意:在运行时或需要创建json对象时,我不知道需要什么数据和/或类型.因此,我不能只创建一个像这样的对象
type Foo struct {
A string `json:"a"`
B int `json:"b"`
}
Run Code Online (Sandbox Code Playgroud) 我有一个问题是将JSON响应解组到结构中.我遇到的问题是邮政编码可以作为字符串或整数返回.如何编写unmarshal方法来检查zip是否为int并强制它将其存储为字符串?
结构:
type CustomerAddress struct {
Line1 string `json:"line1"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
IsPrimaryAddress string `json:"isPrimaryAddress"`
}
Run Code Online (Sandbox Code Playgroud)
示例Json:
address": [
{
"line1": "555 ADDRESS PLACE",
"city": "DALLAS",
"state": "TX",
"isPrimaryAddress": "Y",
"zip": 55555
}
]
Run Code Online (Sandbox Code Playgroud)
解组后,结果应该将zip成功转换为字符串:
address": [
{
"line1": "555 ADDRESS PLACE",
"city": "DALLAS",
"state": "TX",
"isPrimaryAddress": "Y",
"zip": "55555"
}
]
Run Code Online (Sandbox Code Playgroud)
作为尝试,我尝试使用ZipWrapper.
type CustomerAddress struct {
Line1 string `json:"line1"`
City string `json:"city"`
State string `json:"state"`
Zip ZipWrapper `json:"zip"`
IsPrimaryAddress string `json:"isPrimaryAddress"`
}
type …Run Code Online (Sandbox Code Playgroud)