【问题标题】:Unable to unmarshal json into protobuf message无法将 json 编组为 protobuf 消息
【发布时间】: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 的官方包,我想知道是否有人知道为什么会发生这种行为。 jsonpbencoding/json 的默认行为是否不同,可以解释一个能够解组而另一个不能?如果是这样,应该在哪里相应地配置jsonpb 的行为?

【问题讨论】:

    标签: json go protocol-buffers


    【解决方案1】:

    encoding/json 的默认行为如下:

    1. 允许使用未知字段,即,如果字段不匹配,则直接忽略它而不会引发错误。
    2. 在忽略之前,解码器会尝试匹配字段而不区分大小写

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多