可靠地将任何对象转换为字符串,然后再次转换回来

2022-09-01 02:48:38

有没有可靠的方法可以将任何对象转换为字符串,然后再转换回同一对象?我见过一些例子,人们使用转换它们,然后将该值传递给构造函数以再次重建对象,但并非所有对象都有这样的构造函数,因此该方法不适用于所有情况。什么方式会?toString()


答案 1

是的,它被称为序列化

 String serializedObject = "";

 // serialize the object
 try {
     ByteArrayOutputStream bo = new ByteArrayOutputStream();
     ObjectOutputStream so = new ObjectOutputStream(bo);
     so.writeObject(myObject);
     so.flush();
     serializedObject = bo.toString();
 } catch (Exception e) {
     System.out.println(e);
 }

 // deserialize the object
 try {
     byte b[] = serializedObject.getBytes(); 
     ByteArrayInputStream bi = new ByteArrayInputStream(b);
     ObjectInputStream si = new ObjectInputStream(bi);
     MyObject obj = (MyObject) si.readObject();
 } catch (Exception e) {
     System.out.println(e);
 }

答案 2

这是代码:

try {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ObjectOutputStream so = new ObjectOutputStream(bo);
    so.writeObject(stringList);
    so.flush();
    redisString = new String(Base64.encode(bo.toByteArray()));       
} 
catch (Exception e) {
    e.printStackTrace();
}

try {
    byte b[] = Base64.decode(redisString.getBytes()); 
    ByteArrayInputStream bi = new ByteArrayInputStream(b);
    ObjectInputStream si = new ObjectInputStream(bi);
    List<String> stringList2 = (List<String>)si.readObject();
    System.out.println(stringList2.get(1));          
} 
catch (Exception e) {
    e.printStackTrace();         
}