Adib Rastegarnia
Adib Rastegarnia

Reputation: 574

Convert Protobuf to Java

I know it is possible to convert protobuf messages to Java classes. I would like to know is is possible to convert a protobuf message to a Java object without writing translator functions?

Upvotes: 1

Views: 11657

Answers (1)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

Yes it's possible. Use protobuf converters. Check: https://github.com/BAData.

Converting domain object to Protobuf:

ProtoObject protoObject =
    Converter.create().toProtobuf(ProtoObject.class, domainObject);

Converting Protobuf object to domain object:

DomainObject domainObject = Converter.create().toDomain(DomainObject.class, protoObject)

Your domain class needs to be annotated with @ProtoClass, specifying the proto class you want the domain class mapped to. Example:

@ProtoClass(ProtoObject.class)
Class DomainClass{
  @ProtoField
  private String field1;
  @ProtoField(name = "xyz") // in case proto and domain class field have different names
  private String field2;
}

I've been using this and it's quite easy to use and saves a lot of efforts.

Upvotes: 4

Related Questions