部分JSON在Go中解组成一张地图

我的websocket服务器将接收和解组JSON数据。 这些数据总是被封装在一个带有键/值对的对象中。 密钥string将作为值标识符,告诉Go服务器它是什么样的价值。 通过知道什么types的值,然后我可以继续JSON解组的值到正确的types的结构。

每个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) } 

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

这可以通过解组为map[string]*json.RawMessage

 var objmap map[string]*json.RawMessage err := json.Unmarshal(data, &objmap) 

为了进一步parsingsendMsg ,你可以这样做:

 var s sendMsg err = json.Unmarshal(*objmap["sendMsg"], &s) 

比方say ,你可以做同样的事情,解组成一个string:

 var str string err = json.Unmarshal(*objmap["say"], &str) 

除了Stephen Weinberg的回答,我已经实现了一个名为iojson的方便工具,它可以帮助将数据轻松填充到现有对象,并将现有对象编码为JSONstring。 iojson中间件也提供与其他中间件一起工作。 更多的例子可以在https://github.com/junhsieh/iojsonfind

例:

 func main() { jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}` car := NewCar() i := iojson.NewIOJSON() if err := i.Decode(strings.NewReader(jsonStr)); err != nil { fmt.Printf("err: %s\n", err.Error()) } // populating data to a live car object. if v, err := i.GetObjFromArr(0, car); err != nil { fmt.Printf("err: %s\n", err.Error()) } else { fmt.Printf("car (original): %s\n", car.GetName()) fmt.Printf("car (returned): %s\n", v.(*Car).GetName()) for k, item := range car.ItemArr { fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName()) } for k, item := range v.(*Car).ItemArr { fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName()) } } } 

示例输出:

 car (original): My luxury car car (returned): My luxury car ItemArr[0] of car (original): Bag ItemArr[1] of car (original): Pen ItemArr[0] of car (returned): Bag ItemArr[1] of car (returned): Pen