小编典典

部分JSON解组到Go中的地图

go

我的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)
}

感谢您的任何建议/帮助!


阅读 300

收藏
2020-07-02

共1个答案

小编典典

可以通过将其编组为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
}

示例:https//play.golang.org/p/OrIjvqIsi4-

2020-07-02