首页 > 代码库 > google的protocol buffers 对象的序列化 for java

google的protocol buffers 对象的序列化 for java

前言:

protobuf确实比JSON快很多倍,看下面的图就知道了。

技术分享

环境:

win7 x64

eclipse 4.3

protoc-2.5.0

安装包下载:

https://code.google.com/p/protobuf/downloads/list

2.6+的版本已转到GitHub上,下载地址是:

https://github.com/google/protobuf/releases

1.生成jar包

下载ProtoBuf包和生成protobuf-2.5.0.jar文件。下载protoc-2.5.0-win32.zip和protobuf-2.5.0.zip,两个文件都解压缩,将protoc-2.5.0-win32中的protoc.exe文件拷贝到protobuf-2.5.0\src目录下,然后进入protobuf-2.5.0\java,执行 mvn install,编译完成后可以在protobuf-2.5.0\java\target目录中找到protobuf-2.5.0.jar文件。

2.建立eclipse项目

  a.  protoc.exe 放在工程的根目录下面

  b. protobuf-java-2.5.0.jar 放在lib下面

  c.  新建一个文件夹proto存放proto文件

 d. 在proto文件夹下新建一个文件msg.proto,写入以下内容:

option java_package = "com.jamesfen.protobuf"; 
option java_outer_classname = "PersonProbuf"; 


message Person { 
  required string name = 1; 
  required int32 id = 2; 
  optional string email = 3; 


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


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


  repeated PhoneNumber phone = 4; 


  message CountryInfo {
          required string name = 1;
          required string code = 2;
          optional int32 number = 3;
  }
} 


message AddressBook { 
  repeated Person person = 1; 
}

3.产生protobuf JAVA类

进入  cd E:/Git/myhadoop2.x/myhadoop2.x文件夹

执行:

protoc --java_out=./src/main/java   ./proto/msg.proto

在包package com.jamesfen.protobuf;下面会找到类PersonProbuf

4.序列化反序列化测试:

package com.jamesfen.protobuf;
import java.util.List;
import com.google.protobuf.InvalidProtocolBufferException;
import com.jamesfen.protobuf.PersonProbuf;
import com.jamesfen.protobuf.PersonProbuf.Person;
import com.jamesfen.protobuf.PersonProbuf.Person.PhoneNumber;
public class TestProtobuf {

	/**
	* @param args
	*/
	public static void main(String[] args) {
	// TODO Auto-generated method stub
	PersonProbuf.Person.Builder builder = PersonProbuf.Person.newBuilder();
	builder.setEmail("kkk@email.com");
	builder.setId(1);
	builder.setName("TestName");
	builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("131111111").setType(PersonProbuf.Person.PhoneType.MOBILE));
	builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("011111").setType(PersonProbuf.Person.PhoneType.HOME));
	Person person = builder.build();
	byte[] buf = person.toByteArray();
	try {
	Person person2 = PersonProbuf.Person.parseFrom(buf);
	System.out.println(person2.getName() + ", " + person2.getEmail());
	List<PhoneNumber> lstPhones = person2.getPhoneList();
	for (PhoneNumber phoneNumber : lstPhones) {
	System.out.println(phoneNumber.getNumber());
	}
	} catch (InvalidProtocolBufferException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}
	System.out.println(buf);
	}

}

5. 输出:

TestName, kkk@email.com
131111111
011111
[B@472a2a50

6.demo源码下载

https://github.com/Bellonor/myhadoop2.x

google的protocol buffers 对象的序列化 for java