①文件名:message.proto(required属性没有用,建议少用)
option java_package = "org.test"; //包名
option java_outer_classname = "MessagePB";//生成java文件名
message Message {
optional Header header = 1;//头对象
optional MsgContent msgContent = 2;//体对象
message Header {
optional string version = 1;
optional DeviceInfo deviceInfo = 2;
optional string appType = 3;
optional string bizType = 4;
}
message MsgContent {
optional string businessType = 1;//属性值
repeated Txn txn = 2;//多行属性方法
optional Txn txnInfo = 3;//单行属性方法
}
message DeviceInfo {
optional string mac = 1;
optional string imei = 2;
optional string imsi = 3;
optional string deviceId = 4;
}
message Txn {
optional string txnType = 1;
optional string termTraceNo = 2;
optional string termTxnTime = 3;
optional string amt = 4;
optional string txnFlag = 5;
optional string orderId = 6;
optional string idTxn = 7;
optional string authCode = 8;
optional string txnTime = 9;
optional string signFlag = 10;
optional string cardOrg = 11;
optional string issuer = 12;
optional string errorCode = 13;
optional string errorMsg = 14;
optional string merchantId = 15;
optional string merchantName = 16;
optional string shortPan = 17;
optional string txnDate = 18;
optional string terminalId = 19;
optional string errorCodeName = 20;
optional string idTxnCtrl = 21;
}
}
②用protoc.exe生成MessagePB的java类,放cmd命令框执行就可以了
E:\soft\protoc-2.6.1-win32\protoc --proto_path=E:\Java\IDE\myplugins\protocbuf --java_out=E:\Java\IDE\myplugins\protocbuf\java\ E:\Java\IDE\myplugins\protocbuf\message.proto
③MessagePB类的使用(protobuf是不可以自己new对象,如果要设置属性值,需用newBuilder()生成Builder对象,然后build生成需要原对象数据)
MessagePB.Message.Builder messagebuilder = MessagePB.Message.newBuilder();
MessagePB.Message.MsgContent.Builder msgContentbuilder = messagebuilder.getMsgContentBuilder();
//messagebuilder.clearMsgContent();//慎用clear方法,如果在messagebuilder.getMsgContentBuilder()之后用当前方法,下面msgContentbuilder里面的属性值有可能取不到
MessagePB.Message.Header.Builder headerBuilder = messagebuilder.getHeaderBuilder();
MessagePB.Message.Txn.Builder txn = msgContentbuilder.getTxnInfoBuilder();
txn.setMerchantId("111");
txn.setMerchantName("111");
txn.setTerminalId("111");
txn.setIssuer("111");
MessagePB.Message.Txn.Builder txnb = MessagePB.Message.Txn.newBuilder();
txnb.setMerchantId("111");
txnb.setMerchantName("111");
txnb.setTerminalId("111");
txnb.setIssuer("111");
msgContentbuilder.addTxn(txnb);
headerBuilder.setAppType("1");
headerBuilder.setAppVersion("4.1");
msgContentbuilder.setFirst("1");
MessagePB.Message message=messagebuilder.build();
System.out.println(message.getHeader().getAppType()+"++++++++"+headerBuilder.getAppType());
System.out.println(message.getMsgContent().getTxnCount());