douzhaobo6488 2018-06-22 02:25
浏览 46
已采纳

ProtoBuf解组密钥:[[“ abc”,“ 123”],[“ 123”]]

How do you unmarshal a list of list of strings?

Something like:

// Tried repeated string ... ListOfString.... repeated list of string
message Link {
        string id     = 1;
        string names = 2;    
}

jsonstr := `
{
   "names": [ ["Bill", "Susan"], ["Jim", "James"] ]
}`

// go code
jsonpb.Unmarshal(jsonstr, &pb.Link)

Using jsonpb to unmarshal: https://godoc.org/github.com/golang/protobuf/jsonpb

Get json: cannot unmarshal array into Go value

  • 写回答

1条回答 默认 最新

  • drrqwokuz71031449 2018-06-26 13:48
    关注

    There is no Protocol Buffer schema that corresponds to the given JSON. The JSON support in Protocol Buffers is really intended for defining JSON serialization for existing Protocol Buffer messages. You can't use Protocol Buffers as a schema for arbitrary JSON, it's simply not designed to do that.

    In particular, Protocol Buffers lets you define an array as a repeated field, but the field type must have some non-array type, like a message, primitive, or enum.

    The best you can do is change the schema:

    message Name {
        repeated string name = 1;
    }
    
    message Link {
        string id = 1;
        repeated string names = 2;
    }
    

    And then you can change the JSON to match:

    const jsonStr = `
    {
      "names": [
        { "name": ["Bill", "Susan"] },
        { "name": ["Jim", "James"] }
      ]
    }
    `
    
    func main() {
        var link pb.Link
        if err := jsonpb.UnmarshalString(jsonStr, &link); err != nil {
            fmt.Println("Error:", err)
        }
    }
    

    If your JSON format is a hard requirement, then you must deserialize the JSON in some other way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵