Suppose you have some foundation for PROTOBUF, no use, no relationship.
Use Protobuf 3.5.0 to write proto files here
Syntax = "Proto3";
Package tutorial;
Option Java_package = "Com.spy.test.protobuf.model";
Option Java_outer_classname = "Userv3proto";
User domain Comment
/* user domain comment*/message
user{
Int64 user_id = 1;
string user_code = 2;
String user_name =3;
string email =4;
Int32 age = 5;
Repeated string roles = 6;
Map<string, string> address=7;
generating Java class files
Protoc Userv3.proto--java_out=./ write serialization and deserialization unit tests
Userv3proto.user User = UserV3Proto.User.newBuilder ().
Setuserid (2L)
. Setusercode ("00001")
. Setusername ("CC")
. Setage
. Addroles ("admin").
addroles ("cc").
putaddress ("A", "1")
. Putaddress ("B", "2")
. Build ();
byte[] bytes = User.tobytearray ();
Log.debug ("{}", bytes);
Log.debug ("{}", bytes.length);
Deserialization of
Userv3proto.user user2 = UserV3Proto.User.parseFrom (bytes);
Log.debug ("{}", user2.tostring ());
serialized stream of code
[8, 2, 18 5, 48, 48, 48, 48, 49, 26, 2, 99, 99, 40, 20, 50, 5, 97, 100, 109, 105, 110, 50, 2, 99, 99, 58, 6 8, 1, 49, 58, 6, 10, 1, 98, 18, 1, 50]
The following is an analysis of these stream streams and is gradually disassembled to each field . Tobytearray () source Analysis
Write int
Through the above process, found that write a tag, this value is the field ordinal (FieldNumber) left 3-bit, or on the field type, get a value of 8, and then the value of 2 output, that is:
User_id:8, 2, writing string
Take User_code as an example:
Similarly, a tag is first written with a value of (2<<3|2) = 18, then a string, that is:
User_code:18, 5, +, +, +, and write array
Take role for example here
In fact, the array role here is to loop out a string, which is not overly descriptive, that is:
ROLE:50, 5, 97, 100, 109, 105, 110,
ROLE:50, 2, write map
Take address for example here
This begins the serialization of the map field
Output for each item in a map
First output tag,58 (own calculation, IBID.)
Here we begin to output the specific contents of the map
The total serialized size of key and value was first exported, 6
Serialization of key and value content output, type index (key or value) size + length size + specific content
That
-Address 58, 6, 10, 1, 97, 18, 1, 49,
-Address 58, 6, 10, 1, 98, 18, 1, 50
Summarize:
-User_id:8, 2,
-User_code:18, 5, 48, 48, 48, 48, 49,
-User_name:26, 2, 99, 99,
-Age:40, 20,
-Role:50, 5, 97, 100, 109, 105, 110,
-Role:50, 2, 99, 99,
-address:58, 6, 10, 1, 97, 18, 1, 49,
-ADDRESS:58, 6, 1, 1, parseform () source Analysis
Through the above screenshot, you can visually see the specific field based on tag, and then assign a value.
Complete.