I have an existing system, which is using protobuf-based communication protocol between GUI and server. Now I would like to add some persistence, but at the moment
Here is my utility class, you may use:
package <removed>;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
* Author @espresso stackoverflow.
* Sample use:
* Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
Model.Person res = personSvc.update(reqObj);
final String resJson = ProtoUtil.toJson(res);
**/
public class ProtoUtil {
public static <T extends Message> String toJson(T obj){
try{
return JsonFormat.printer().print(obj);
}catch(Exception e){
throw new RuntimeException("Error converting Proto to json", e);
}
}
public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
try{
Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
JsonFormat.parser().ignoringUnknownFields().merge(protoJsonStr,builder);
T out = (T) builder.build();
return out;
}catch(Exception e){
throw new RuntimeException(("Error converting Json to proto", e);
}
}
}
For protobuf 2.5, use the dependency:
"com.googlecode.protobuf-java-format" % "protobuf-java-format" % "1.2"
Then use the code:
com.googlecode.protobuf.format.JsonFormat.merge(json, builder)
com.googlecode.protobuf.format.JsonFormat.printToString(proto)
We are currently using protobuf-java-format to convert our Protobuf messages (anything subclass of Message
) into a JSON format to send over our web API.
Simply do:
JsonFormat.printToString(protoMessage)