Java: JSON -> Protobuf & back conversion

后端 未结 9 2017
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 10:59

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

相关标签:
9条回答
  • 2020-12-02 11:50

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 11:51

    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)
    
    0 讨论(0)
  • 2020-12-02 11:54

    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)
    
    0 讨论(0)
提交回复
热议问题