Erez Ben Harush
Erez Ben Harush

Reputation: 855

Write Java protobuf class to custom JSON fomat

I am trying to find the best approach to print multiple protobuf generated Java classes to a custom human readable JSON format.

Given following code that uses Java class generated from protobuf:

Person.Builder personBuilder = PersonData.newBuilder();
Person person = personBuilder
  .setName("John Doe")
  .setAge("99")
  .build();

The following is the default JSON representation when using new JsonFormat().printToString(person):

{ "name": "John Doe", "age":99 }

The desired JSON representation is:

"John Doe":{
  "age":99
}

Is there a common generic way to achieve the above for multiple protobuf models?

Upvotes: 0

Views: 770

Answers (1)

jayaram S
jayaram S

Reputation: 580

You could achieve that by converting from Person object to a Map structure and place the name-value pairs are you choose. Natively, the JsonFormat will adhere to the spec https://developers.google.com/protocol-buffers/docs/proto3 If you move the name of the person to the name of the object, it might make interoperability harder - depending on what you are trying to do with it of course.

Upvotes: 1

Related Questions