Go中的部分JSON解组成地图 [英] Partly JSON unmarshal into a map in Go

查看:120
本文介绍了Go中的部分JSON解组成地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的websocket服务器将接收和解组JSON数据。这些数据将始终用键/值对包装在一个对象中。键串将作为值标识符,告诉Go服务器是什么样的价值。通过知道什么类型的值,我可以继续JSON将这个值解组成正确的结构类型。



每个json对象可能包含多个键/值对。



示例JSON:

  {
sendMsg :{user:ANISUS,msg:尝试发送消息},
说:你好
}

使用encoding / json包是否有任何简单的方法? p>

  package main 

import(
encoding / json
fmt


//sendMsg-command
的值的结构类型sendMsg struct {
用户字符串
msg string
}
//say-command
类型的值的类型表示字符串

func main(){
data:= [] byte (`{sendMsg:{user:ANISUS,msg:尝试发送消息},说:你好}`)

//这个将不会工作,因为json.MapObject([]字节)不存在
o bjmap,err:= json.MapObject(data)

//这是我希望objmap包含
// var objmap = map [string] [] byte {
//sendMsg:[] byte(`{user:ANISUS,msg:尝试发送消息}`),
//say:[] byte `你好`),
//}
fmt.Printf(%v,objmap)
}

感谢任何建议/帮助!

解决方案

这可以是通过解组成一个 map [string] json.RawMessage 完成。

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

要进一步解析 sendMsg ,您可以执行以下操作:

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

对于,你可以对字符串做同样的事情和解散:

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


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.

Each json-object might contain multiple key/value pairs.

Example JSON:

{
    "sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
    "say":"Hello"
}

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!

解决方案

This can be accomplished by Unmarshalling into a map[string]json.RawMessage.

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

To further parse sendMsg, you could then do something like:

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

For say, you can do the same thing and unmarshal into a string:

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

这篇关于Go中的部分JSON解组成地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆