【protobuf】protobuf和json相互转化

protobuf和json相互转化

//Protocol_demo类

从pb转化json

Protocol_demo.Response.Builder builder = Protocol_demo.Response.newBuilder();
Message message=builder.build();
public static  String protobufToJson(Message message) {
         String jsonFormat =JsonFormat.printToString(message);  
        return jsonFormat;
}

从json转protobuf

Protocol_100.Response.Builder builder =Protocol_100.Response.newBuilder();

                        try {
                            JsonFormat.merge(jsonFormat, builder);
                        } catch (com.googlecode.protobuf.format.JsonFormat.ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        Protocol_100.Response rb=builder.build();
                        System.out.println("getId:" + rb.getPlayer().getId());  
                        System.out.println("getName:" + rb.getPlayer().getName());  

pom.xml配置

    
        com.googlecode.protobuf-java-format
        protobuf-java-format
        1.2
    


 

你可能感兴趣的:(protobuf)