Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protobuf JsonFormater.printer convert long to String in Json

Currently I encounter a behavior of JsonFormater.printer printing the long(fixed64) value as String in JSON. Is there any way/option to set the JsonFormater.printer not to do this conversion (Long(fixed64) -> String in Json)? The Json is consumed by Java app, representing fixed64 as integer in JSON should not be a problem for Java.

Here is the code: In data.proto

syntax = "proto2";
message data{
  required fixed64 user_id = 1;
  required int32 member_id = 2
}

Here is the java code, the file format is *.pb.gz

import com.google.protobuf.util.JsonFormat;
.......
//print data in JSON format
final InputStream input = new GZIPInputStream(new FileInputStream(pathToFile));
Message m;
m = defaultMsg.getParserForType().parseDelimitedFrom(input));
String jsonString = JsonFormat.printer().preservingProtoFieldNames().omittingInsignificantWhitespace().print(m);

Generated Java class: Data.java (Generated with protoc 2.6.1)

...
private long userId_;
...
private int memberId_;
...

expected result: {"user_id":6546585813946021349,member_id":7521}

actual result: {"user_id":"6546585813946021349",member_id":7521}

The user_id is String in json, but I want it as integer

Thanks David

like image 357
user3422290 Avatar asked Sep 15 '25 03:09

user3422290


1 Answers

It seems this is by design, according to the source code. UINT64 and FIXED64 types are always printed out with surrounding double quotes, no questions asked:

https://github.com/protocolbuffers/protobuf/blob/f9d8138376765d229a32635c9209061e4e4aed8c/java/util/src/main/java/com/google/protobuf/util/JsonFormat.java#L1081-L1084

    case INT64:
    case SINT64:
    case SFIXED64:
      generator.print("\"" + ((Long) value).toString() + "\"");

In that same file, a few lines above, you can see that INT32 types are only double quoted if they're keys in a map (which your proto obviously doesn't have).

So, I'd ask for more information on the protobuf mailing list, or maybe report it as a bug/feature-request.

like image 188
mjuarez Avatar answered Sep 17 '25 17:09

mjuarez