protobuf嵌套java反序列化_基于protobuf2.6序列化 反序列化

序列化、反序列化工具类:

package org.cgl.util.protobuf26;

import com.google.protobuf.GeneratedMessage;

import com.google.protobuf.TextFormat;

import org.cgl.util.protobuf26.message.Message;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

/**

* Created by agui on 3/14/2017.

*/

public class ProtoBufUtil {

public static String shortDebugString(GeneratedMessage gmsg){

return null == gmsg? "空": TextFormat.shortDebugString( gmsg);

}

public static String to_binaray(GeneratedMessage.Builder builder) throws IOException {

ByteArrayOutputStream bs = new ByteArrayOutputStream();

bs.write(builder.build().toByteArray());

return bs.toString(Name.ISO_8859_1);

}

public static String to_binaray(GeneratedMessage msg_obj) throws IOException {

ByteArrayOutputStream bs = new ByteArrayOutputStream();

bs.write(msg_obj.toByteArray());

String msg_bin = bs.toString(Name.ISO_8859_1);

return msg_bin ;

}

//String msg_bin...

//TrmRtrDvcAgtSvGgPrtbf.Cmd cmd_default_to_net_g = TrmRtrDvcAgtSvGgPrtbf.Cmd.parseFrom(msg_bin.getBytes("iso-8859-1"))

public static GeneratedMessage to_object(Class msg_clz, String msg_bin) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {

byte[] msg_bin0 = msg_bin.getBytes(Name.ISO_8859_1);

Method parseFrom_method = msg_clz.getMethod("parseFrom",byte[].class);

Object msg_obj = parseFrom_method.invoke(null, msg_bin0);

return (GeneratedMessage) msg_obj;

}

public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {

/**

* 将 req 序列化为 req_bin_string , 再将 req_bin_string 反序列化为 req_object_from_bin_string

*/

Message.LoginRequest req = Message.LoginRequest.newBuilder().setApplicationId(10).setUserName("zhangsan").setPasswordMd5("aaaaaaaaaaaaaaaaaaaa").build();

String message = null;

String req_bin_string = to_binaray(req);

Message.LoginRequest req_object_from_bin_string = (Message.LoginRequest) to_object(Message.LoginRequest.class, req_bin_string);

//req_object_from_bin_string 和 req 一样的

int debug = 0;

}

}

命令(常量)类:

package org.cgl.util.protobuf26;

/**

* Created by agui on 4/22/2017.

*/

public class Name {

public static final String ISO_8859_1 = "ISO-8859-1";

}

protobuf报文定义:

option java_package = "org.cgl.util.protobuf26.message";

option java_outer_classname = "Message";

message LoginRequest{

optional int32 applicationId = 1;

optional string userName = 2;

optional string passwordMd5 = 3;

}

生成报文解析器命令:

protoc message.proto --java_out=.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值