Java 實現grpc實例--json轉protobuf

java和python使用grpc交互 參考文章:

https://blog.csdn.net/zhj_fly/article/details/82684970

如上鍊接中講的已經很清楚了,相同的內容不再贅述,這裏只說下用Java實現grpc客戶端代碼的時候,如何直接解析參數到對應的類中(即直接將json轉爲protobuf)。

public void greet(String name) {
    Map<String, Object> map = new HashMap<>();
    map.put("name","zhangsan");
    logger.info("Will try to greet " + name + " ...");
    //HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    JSONObject jsonObject =JSONObject.parseObject(JSON.toJSONString(map));
    String jsonStr = jsonObject.toJSONString();
    //json > pb
    HelloRequest.Builder newBuilder = HelloRequest.newBuilder();
    try {
        JsonProtoFormat.merge(jsonStr, newBuilder);
    } catch (JsonProtoFormat.ParseException e) {
        e.printStackTrace();
    }
    try {
        response = blockingStub.sayHello(newBuilder.build());
    } catch (StatusRuntimeException e) {
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Greeting: " + response.getMessage());
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章