使用Protostuff保留未知字段

时间:2014-10-21 09:07:32

标签: java xml protocol-buffers protostuff

我有这个Java代码(source):

// Deserialize
Person person = new Person();
InputStream in;
XmlIOUtil.mergeFrom(in, person, Person.getSchema());

// Do stuff...

// Serialize back into XML
OutputStream out;
XmlIOUtil.writeTo(out, person, Person.getSchema());

假设我的XML代码包含未知的字段,这些字段不在模式中(即提供的XML是由较新版本的软件生成的)。

当我再次序列化这些字段时,是否有一种漂亮,干净的方法来保存这些字段?我知道Protocol Buffers preserves unknown fields

一种解决方案是将原始XML复制到缓冲区中,然后将新序列化的XML与原始XML合并,但这似乎过于复杂。

2 个答案:

答案 0 :(得分:0)

根据a post on the Protostuff forum,似乎不支持保留未知字段:

  
    

我认为Protobuf序列化(它是Protostuff的一部分)能够处理谷歌提供的库所做的任何事情。如果我选择使用Protostuff,那么扩展名是&可用的未知领域?

  
     

不,不。未知字段将被忽略。

答案 1 :(得分:0)

以下是protoc编译器的示例输出片段:

void hello_message::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:trustportal.crypt.rpc.hello_message)
  // required string welcome_message = 1;
  if (has_welcome_message()) {
    ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
      this->welcome_message().data(), this->welcome_message().length(),
      ::google::protobuf::internal::WireFormat::SERIALIZE,
      "welcome_message");
    ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
      1, this->welcome_message(), output);
  }

  if (!unknown_fields().empty()) {
    ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
        unknown_fields(), output);
  }
  // @@protoc_insertion_point(serialize_end:trustportal.crypt.rpc.hello_message)
}

似乎暗示未知字段将被正确序列化。