为什么 Protobuf 的 fromJson() 函数在 Dart 中不起作用

Pat*_*ckB 4 protocol-buffers dart flutter

我对 fromJson() 函数有疑问。

我尝试使用从 Firestore 收到的数据构建 protobuf,但 fromJson() 似乎无法解析它。面对这个问题,我决定通过手动创建一个新的空Protobuf进行测试,将其导出为JSON并使用json创建一个新的protobuf。我遇到了一些奇怪的问题:

MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";

...
// Exporting using writeToJson()
 String json1 = my_protobuf.writeToJson(); // All my keys are numbers.. why?

// Exporting using a Map
Map<String, dynamic> json2_map = info_to_write.toProto3Json();
String json2 = JsonEncoder().convert(json2_map); // Seems to be a normal JSON

// Build a protobuf from JSON
MyProtobuf new_protobuf1 = MyProtobuf.fromJson(json1);  // Exception thrown
MyProtobuf new_protobuf2 = MyProtobuf.fromJson(json2); // Exception thrown
Run Code Online (Sandbox Code Playgroud)

这是我没有使用这个好功能的错误吗?

这是我的原型文件:

syntax = "proto3";

package test.v1;

message MyProtobuf {
    string id = 1;
    string name = 2;
}
Run Code Online (Sandbox Code Playgroud)

ישו*_*ותך 7

要将消息转换为 json 字符串,需要使用以下代码:

MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";
...

// convert to json object
var obj = my_protobuf.toProto3Json();

// encode to json string
var value = jsonEncode(obj);
Run Code Online (Sandbox Code Playgroud)

要将 json 字符串解码为 protobuf 消息,请使用以下命令:

var jsonString = ".....";

// decode to json object
var obj = jsonDecode(docJson);

var my_protobuf = MyProtobuf.create()..mergeFromProto3Json(obj);
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/google/protobuf.dart/issues/220#issuecomment-863250957