Java: JSON -> Protobuf & back conversion

后端 未结 9 2081
隐瞒了意图╮
隐瞒了意图╮ 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 ;
    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  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 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);
            }
        }
    }
    

提交回复
热议问题