简体   繁体   English

使用protobuf进行序列化时出错

[英]error with serialization with protobuf

I'm trying to serialize a structure with protobuf. 我正在尝试使用protobuf序列化结构。 after many hours trying to figure out what I'm doing wrong I decided to test the google's example and it didn't worked as well 经过几个小时试图弄清楚我做错了什么我决定测试google的例子,但是效果并不好

I have the following protocol from google ( https://developers.google.com/protocol-buffers/docs/javatutorial ): 我有以下谷歌协议( https://developers.google.com/protocol-buffers/docs/javatutorial ):

package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";

message Person {
    required string name = 1;
    required int32 id = 2;
    optional string email = 3;
    repeated PhoneNumber phone = 4;

    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
    }

    message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
    }
}

message AddressBook {
    repeated Person person = 1;
}

and I'm trying to serialize it with: 我正在尝试将其序列化:

Person john = Person.newBuilder()   
    .setId(1234)
    .setName("John Doe")
    .setEmail("jdoe@example.com")
    .addPhone(
        Person.PhoneNumber.newBuilder()
            .setNumber("555-4321")
            .setType(Person.PhoneType.HOME))
    .build();

byte[] serialized = john.toByteArray(); byte [] serialized = john.toByteArray();

and I get "java.lang.UnsupportedOperationException: This is supposed to be overridden by subclasses." 我得到“java.lang.UnsupportedOperationException:这应该被子类覆盖。”

Thanks; 谢谢;

As Marc said, A mismatch in Protocol Buffer versions will give you this exact message. 正如Marc所说,协议缓冲区版本中的不匹配将为您提供这个确切的消息。 In particular if 特别是如果

  • The .proto definition is converted to java using the 2.4.3 (or earlier) protoc.exe 使用2.4.3(或更早版本)的protoc.exe将.proto定义转换为java
  • You use the 2.5.0 protobuffers library 您使用2.5.0 protobuffers库

you will get this message in many methods (eg getParserForType, getUnknownFields) of class GeneratedMessage . 您将在GeneratedMessage类的许多方法(例如getParserForType,getUnknownFields)中获得此消息。 There are no doubt other potential mismatch's that will cause this error 毫无疑问,其他潜在的不匹配会导致此错误


With protocol buffers 2.5.0 it is essential you regenerate all java classes with the 2.5.0 version of protoc (or on windows protoc.exe). 使用协议缓冲区2.5.0必须使用2.5.0版本的protoc(或windows protoc.exe) 重新生成所有java类。


If you do the reverse - run code generated by protoc version 2.5 with the libraries for protocol buffers version 2.4 . 如果你执行反向运行由protoc版本2.5生成的代码与协议缓冲区版本2.4的库。 You will get the following message 您将收到以下消息

java.lang.VerifyError: class xxx.xxx.xx.. 
overrides final method getUnknownFields.()Lcom/google/protobuf/UnknownFieldSet;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM