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 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下