package com.test; import com.alibaba.fastjson.JSON;
import org.junit.Test; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class SerializeTest {
@Test
public void Test()throws Exception{
AgencyVoInfo dept = new AgencyVoInfo();
dept.setAgencyCode("1");
dept.setAgencyName("2");
dept.setBranchCode("3");
dept.setId(1);
dept.setSerialNo(1);
String objectStr = serializeObject(dept);
System.out.println(objectStr);
AgencyVoInfo dept2 = (AgencyVoInfo)stringSerializeObject(objectStr);
System.out.println(JSON.toJSON(dept2));
}
/**
* 对象序列化为字符串
* @param object
* @return
*/
public static String serializeObject(Object object)throws Exception{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
out.writeObject(object);
//必须是ISO-8859-1
String objectStr = byteArrayOutputStream.toString("ISO-8859-1");
out.close();
byteArrayOutputStream.close();
return objectStr;
} /**
* 字符串序列化为对象
* @param objectStr
* @return
* @throws Exception
*/
public static Object stringSerializeObject(String objectStr)throws Exception{
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
return object;
}
}