PatrickB
PatrickB

Reputation: 333

Why fromJson() function of Protobuf not working in Dart

I have an issue with the fromJson() function.

I try to build my protobuf with the data received from Firestore and the fromJson() seems to not be able to parse it. Facing this issue, I decide to do a test by creating a new empty Protobuf manually, export it as a JSON and create a new protobuf with the json. I got some weird issues:

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

Is this a bug of Im not using this good function?

This is my proto file:

syntax = "proto3";

package test.v1;

message MyProtobuf {
    string id = 1;
    string name = 2;
}

Upvotes: 4

Views: 3152

Answers (1)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29794

To convert a message to json string, you need to use the following code:

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);

To decode json string to protobuf message, use the following:

var jsonString = ".....";

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

var my_protobuf = MyProtobuf.create()..mergeFromProto3Json(obj);

see https://github.com/google/protobuf.dart/issues/220#issuecomment-863250957

Upvotes: 8

Related Questions