I am trying to convert a protobuf object to JSON format using com.googlecode.protobuf.format.JsonFormat but the map type came out unexpected.
My message is like this
message Response {
repeated Candidate candidates = 1;
map<string, ErrorMessage> errors = 2;
}
message ErrorMessage {
string message = 0;
ErrorType type = 1;
}
enum ErrorType {
ERROR = 0;
WARNING = 1;
}
The issue is the JSON format of the Response object I created
Response response = ...
Return new ResponseEntity<>(new JsonFormat().printToString(response), HttpStatus.OK);
I expect the errors be formatted as a map keyed by the string value (of the map key)
...
"errors": {
"someID" : {
"message": "blah blah",
"type": "ERROR"
}
}
However the actual output is (I evaluated only the new JsonFormat().printToString(response) part in intellij)
...
"errors": {
"key": "someID",
"value": {
"message": "blah blah",
"type": "ERROR"
}
}
I hope it's some small configuration I missed to make protobuf (or Jackson?) to be aware of the actual key value ? not using "key" and "value".
BTW, what's the point of having literal "key" and "value" field in a map type ? You can't do constituent lookup with it and you might just use a custom type/object.
This code works perfectly for me:
test.proto
App.java
The output is:
Which has no
keys andvalueas you see. Make sure that you printed not the message itself, but the result ofJsonFormat.printer().print(). Basically,keyandvalues you've seen are from internaltoString()implementation of ProtobufMessage.And the full class name for
JsonFormatiscom.google.protobuf.util.JsonFormat, notcom.googlecode.protobuf.format.JsonFormat.