测试程序
public static void main(String[] args) throws IOException {
// PersonProtos.Person是protobuf生成的java类
PersonProtos.Person.Builder personBuilder = PersonProtos.Person.newBuilder();
// 定义一个相同结构的json类并赋值
JsonObject abb = new JsonObject();
JsonObject cbb = new JsonObject();
JsonObject gbb = new JsonObject();
gbb.addProperty("apply",apply);
gbb.addProperty("none","none");
cbb.addProperty("applies_to_location",applies_to_location);
abb.addProperty("age",21);
abb.addProperty("name","John");
abb.addProperty("email","[email protected]");
abb.add("point_attribution",cbb);
cbb.add("abb",gbb);
String json = abb.toString();
// json转protobuf
JsonFormat.merge(json, personBuilder);
StringBuffer a = new StringBuffer();
// 字符串格式
a.append("age:30,name:'John',email:'[email protected]',point_attribution {applies_to_location: 2.0,abb {\n" +
" apply: 1.0\n" +
" }\n" +
"}");
// 文本转protobuf
TextFormat.merge(a.toString(),personBuilder);
System.out.println(TextFormat.printToString(personBuilder.build()));
System.out.println(JsonFormat.printToString(personBuilder.build()));
}