对象 & byte数组之间转化工具类
效果图:objectToByteArray: [B@7d4991ad
byteArrayToObject: WXOrderMsgEntity(uuid=null, orderSeq=W2018052100000002, carportSeq=1001, stakeSeq=102)
{"carportSeq":1001,"orderSeq":"W2018052100000002","stakeSeq":102}
package com.extracme.echarge;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Message;
import com.extracme.evready.charge.define.WXOrderMsgEntity;
public class TestHalp {
public static void main(String[] args) {
WXOrderMsgEntity msg=new WXOrderMsgEntity();
msg.setCarportSeq(1001);
msg.setOrderSeq("W2018052100000002");
msg.setStakeSeq(102);
byte[] objectToByteArray = objectToByteArray(msg);
System.err.println("objectToByteArray: " + objectToByteArray);
Message message=new Message();
message.setBody(objectToByteArray);
Object byteArrayToObject = byteArrayToObject(message.getBody());
System.err.println("byteArrayToObject: " + byteArrayToObject.toString());
WXOrderMsgEntity d=(WXOrderMsgEntity)byteArrayToObject;
System.out.println(JSON.toJSONString(d));
}
/**
* 对象转Byte数组
* @param obj
* @return
*/
public static byte[] objectToByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
bytes = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
System.err.println("objectToByteArray failed, " + e);
} finally {
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
System.err.println("close objectOutputStream failed, " + e);
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
System.err.println("close byteArrayOutputStream failed, " + e);
}
}
}
return bytes;
}
/**
* Byte数组转对象
* @param bytes
* @return
*/
public static Object byteArrayToObject(byte[] bytes) {
Object obj = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(bytes);
objectInputStream = new ObjectInputStream(byteArrayInputStream);
obj = objectInputStream.readObject();
} catch (Exception e) {
System.err.println("byteArrayToObject failed, " + e);
} finally {
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
System.err.println("close byteArrayInputStream failed, " + e);
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
System.err.println("close objectInputStream failed, " + e);
}
}
}
return obj;
}
}