Java: JSON -> Protobuf & back conversion

后端 未结 9 2086
隐瞒了意图╮
隐瞒了意图╮ 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:40

    Well, there is no shortcut to do it as per my findings, but somehow you
    an achieve it in few simple steps

    First you have to declare a bean of type 'ProtobufJsonFormatHttpMessageConverter'

    @Bean  
    @Primary  
    public ProtobufJsonFormatHttpMessageConverter protobufHttpMessageConverter() {  
      return new ProtobufJsonFormatHttpMessageConverter(JsonFormat.parser(), JsonFormat.printer());  
    }  
    

    Then you can just write an Utility class like ResponseBuilder, because it can parse the request by default but without these changes it can not produce Json response. and then you can write few methods to convert the response types to its related object type.

    public static  T build(Message message, Class type) {
      Printer printer = JsonFormat.printer();
      Gson gson = new Gson();
      try {
        return gson.fromJson(printer.print(message), type);
      } catch (JsonSyntaxException | InvalidProtocolBufferException e) {
        throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Response   conversion Error", e);
      }
    }
    

    Then you can call this method from your controller class as last line like -

    return ResponseBuilder.build(, );
    

    Hope this will help you to implement protobuf in json format.

提交回复
热议问题