java实现string与object对象的相互转换。
首先定义一个User类,如下:
class User implements Serializable{
public String name;
public String pwd;
public User(String name,String pwd){
this.name=name;
this.pwd=pwd;
}
}
注意,该类需要序列化,即实现serializable接口。
主体程序如下:
public class Utilty {
public static String objSerToStr(Object objArr) {
String val = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(objArr);
oos.flush();
oos.close();
bos.close();
val = new String(bos.toByteArray(), "ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return val;
}
public static Object strDeserToObj(String str) {
if (null == str) {
return null;
}
Object objArr = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(
str.getBytes("ISO-8859-1"));
ObjectInputStream ois = new ObjectInputStream(bis);
objArr = ois.readObject();
bis.close();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return objArr;
}
public static void main(String[] args) {
User user=new User("google","123");
String str=Utilty.objSerToStr(user);
System.out.println("对象转字符串:"+str);
User u=(User)Utilty.strDeserToObj(str);
System.out.println("name:"+u.name+",pwd:"+u.pwd);
}
}
程序运行截图如下: