登录
首页 >  Golang >  Go问答

Convert/Deserialize Struct to JSON

来源:stackoverflow

时间:2024-03-13 15:21:27 375浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《Convert/Deserialize Struct to JSON》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我需要将 json rpc 消息包装在 go 结构中 这是我的第一个想法,它适用于像这样的传出消息

// message wrapper
type message struct {
    id      *string      `json:"id,omitempty"`
    jsonrpc string       `json:"jsonrpc"`
    method  *string      `json:"method,omitempty"`
    params  *interface{} `json:"params,omitempty"`
    result  *interface{} `json:"result,omitempty"`
}

// newnotification creates a rpc notification
func newnotification(method string, params interface{}) message {

    m := message{}
    m.jsonrpc = "2.0"
    m.method = &method
    m.params = ¶ms

    return m

}

type test struct {
        a string `json:"a"`
        b string `json:"b"`
}

t := test{"abc", "def"}

m := newnotification("testmethod", t)

socket.writejson(m)

但是现在对于接收方向我有一个问题 params *接口{} 声明。

我通过 method 字段识别 params 有效负载类型,并希望 将 params 解组到该结构......但因此我需要类型 json.rawmessage 用于 params 以使其正常工作。

我不想定义 messageinmessageout 结构!

m := Message{}
socket.ReadJSON(m)

t := Test{}

json.Unmarshal(m.Params, &t)

解决方案


您应该使用 json.RawMessage 作为参数和结果字段的类型。这将延迟这些字段的解码,直到您知道接收端的方法是什么。查看文档和示例:这是相同的用例:https://golang.org/pkg/encoding/json/#RawMessage

到这里,我们也就讲完了《Convert/Deserialize Struct to JSON》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>