【发布时间】:2020-06-12 14:29:08
【问题描述】:
我的问题与这个问题几乎相反:Unable to unmarshal json to protobuf struct field
我有一条包含以下形式的嵌套消息的消息:
message MyMsg {
uint32 id = 1;
message Attribute {
...
}
repeated Attribute attrs = 2;
message OtherAttribute {
...
}
OtherAttribute oAttr = 3;
...
}
某些外部依赖项会发送此消息 JSON 形式,然后需要将其解组为 go 结构。当尝试像这样使用jsonpb 时,其中resp 是*http.Response:
msg := &MyMsg{}
jsonpb.Unmarshal(resp.Body, msg)
消息未完全解码到结构中,即缺少一些嵌套结构。然而,当消息被简单地使用encoding/json 解码时:
msg := &MyMsg{}
json.NewDecoder(resp.Body).Decode(msg)
所有属性都成功解码到结构体中。
由于jsonpb 是 protobuf/json 之间 (un)marshall 的官方包,我想知道是否有人知道为什么会发生这种行为。 jsonpb 和 encoding/json 的默认行为是否不同,可以解释一个能够解组而另一个不能?如果是这样,应该在哪里相应地配置jsonpb 的行为?
【问题讨论】:
标签: json go protocol-buffers