Reliably convert any object to String and then back again

后端 未结 7 793
名媛妹妹
名媛妹妹 2020-12-02 13:35

Is there a reliable way to convert any object to a String and then back again to the same Object? I\'ve seen some examples of people converting them using toString()

7条回答
  •  执念已碎
    2020-12-02 13:51

    This is the code:

    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 stringList2 = (List)si.readObject();
        System.out.println(stringList2.get(1));          
    } 
    catch (Exception e) {
        e.printStackTrace();         
    }
    

提交回复
热议问题