使用protobuf序列化时出错 [英] error with serialization with protobuf

查看:3215
本文介绍了使用protobuf序列化时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用protobuf序列化结构。经过几个小时试图找出我做错了什么我决定测试谷歌的例子并且它没有用得好

I'm trying to serialize a structure with 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

我有以下协议来自谷歌( https://developers.google.com/protocol-buffers/docs/javatutorial):

I have the following protocol from google (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();

我得到java.lang.UnsupportedOperationException:这应该被子类覆盖。

and I get "java.lang.UnsupportedOperationException: This is supposed to be overridden by subclasses."

谢谢;

推荐答案

正如Marc所说,协议缓冲区版本中的不匹配将为您提供此确切消息。特别是如果

As Marc said, A mismatch in Protocol Buffer versions will give you this exact message. In particular if


  • 使用2.4.3(或更早版本)protoc.exe将.proto定义转换为java

  • 您使用2.5.0 protobuffers库

您将在许多方法中获得此消息(例如getParserForType,getUnknownFields )类 GeneratedMessage 。毫无疑问,其他潜在的不匹配将导致此错误

you will get this message in many methods (e.g. getParserForType, getUnknownFields) of class GeneratedMessage. There are no doubt other potential mismatch's that will cause this error

协议缓冲区2.5.0 使用2.5.0版本的protoc(或在windows protoc.exe上)重要 重新生成所有java类。

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.4 的库执行 protoc版本2.5 生成的反向运行代码>。您将收到以下消息

If you do the reverse - run code generated by protoc version 2.5 with the libraries for protocol buffers version 2.4. You will get the following message

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

这篇关于使用protobuf序列化时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆