我正在使用protocol buffer
和创建一个示例程序。我的protobuf-java-format
原型文件是
package com.sample;
option java_package = "com.sample";
option java_outer_classname = "PersonProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
我的示例程序是
package com.sample;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import com.google.protobuf.Message;
import com.googlecode.protobuf.format.XmlFormat;
import com.sample.PersonProtos.Person;
/**
* This class generate XML out put from Object and vice-versa
*
* @author mcapatna
*
*/
public class Demo
{
public static void main(String[] args) throws IOException
{
// get the message type from protocol buffer generated class.set the
// required property
Message personProto = Person.newBuilder().setEmail("a").setId(1).setName("as").build();
// use protobuf-java-format to generate XMl from Object.
String toXml = XmlFormat.printToString(personProto);
System.out.println(toXml);
// Create the Object from XML
Message.Builder builder = Person.newBuilder();
String fileContent = "";
Person person = Person.parseFrom(new FileInputStream("C:\\file3.xml"));
System.out.println(XmlFormat.printToString(person));
System.out.println("-Done-");
}
}
XmlFormat.printToString(
) 工作正常。但是从 XML 创建对象不起作用我也尝试过。但是XmlFormat.merge(toXml, builder);
由于merge()
返回 void.so 我们如何获取 Person 类的对象。上述方法merge()
并parseFrom()
给出相同的异常
com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
注意:"C:\\file3.xml"
内容与toXml
.