在将 JSON 字符串解析为 Protobuff 消息时,有没有办法忽略数据类型不匹配?

问题描述 投票:0回答:1

Protobuf 库版本:3.21.12 这是我的原始文件:

syntax = "proto2";

message MyBidRequest {
  optional string req_id = 1;
  optional int32 tmax = 2;
}
    // Read JSON string from a file or any source
    std::string json_string = R"( 
    {
      "req_id": 1,
      "tmax": 777
    }
  )";

    // Create an instance of the protobuf message
    MyBidRequest my_bid_request;

    // Parse the JSON string into the protobuf message

    google::protobuf::util::Status myStatus = google::protobuf::util::JsonStringToMessage(json_string, &my_bid_request);

    std::cout << "Jsonstring to Message Status string:" << myStatus.ToString() << std::endl
  
    // Access the fields of the protobuf message
    std::cout << "1:Field req_id: " << my_bid_request.req_id() << std::endl;
    std::cout << "1:Field tmax: " << my_bid_request.tmax() << std::endl;

运行上述代码的输出:

Jsonstring to Message Status string:INVALID_ARGUMENT:(req_id): invalid value 1 for type TYPE_STRING
1:Field req_id: 
1:Field tmax: 0

即使单个字段的数据类型不匹配,也会发生完整的json解析失败。我想要实现的是,即使id不是字符串,tmax字段也应该被消耗,有没有办法可以实现这一点?

c++ protocol-buffers
1个回答
0
投票

据我所知,所请求的行为对于

google::protobuf::util::JsonStringToMessage
来说是不可能的。通常,protobuf 被设计为在无效消息上完全失败,未实现部分或宽松解析的代码。

作为一种解决方法,您可以在 .proto 文件中拥有多个

message
定义(例如,一个带有
int
,另一个带有
string
),并在每个定义上使用相同的 JSON 输入调用
google::protobuf::util::JsonStringToMessage

通常,如果您更改字段的类型,并且仍然希望能够解析旧消息,那么您应该在 .proto 文件中引入一个新字段,如下所示:

message MyBidRequest {
  oneof req_id_oneof {
    // In new messages (since version X), use .req_id_x instead.
    optional int64 req_id = 1;
    optional string req_id_x = 11;
  }
  optional int32 tmax = 2;
}
© www.soinside.com 2019 - 2024. All rights reserved.