无法将 json 解组为 protobuf 消息

Unable to unmarshal json into protobuf message

我的问题与这个问题完全相反: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 之间(取消)编组的官方软件包,我想知道是否有人知道为什么会发生这种行为。 jsonpbencoding/json 的默认行为是否在某种程度上有所不同,可以解释一个能够解组而另一个不能?如果是这样,在哪里可以相应地配置 jsonpb 的行为?

encoding/json 的默认行为如下:

  1. 允许使用未知字段,即在字段不匹配的情况下,它会被简单地忽略而不会引发错误。
  2. 在它被忽略之前,解码器尝试匹配不区分大小写的字段

第 1 点中的行为可以在 jsonpb 中复制,方法是使用 Unmarshaller 结构并将 属性 AllowUnknownFields 设置为 true

var umrsh = jsonpb.Unmarshaler{}
umrsh.AllowUnknownFields = true
msg := &MyMsg{}
umrsh.Unmarshal(resp.Body, msg)

似乎无法复制 jsonpb 中第 2 点的行为。