对象序列化成字符串乱码解决
问题描述:
将一个对象序列化成字符串后,字符串是乱码的,并且反序列化报错。
代码如下:
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.SerializationUtils;
import java.util.ArrayList;
import java.util.List;
public class TempTest {
public static void main(String[] args) {
List<JSONObject> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("a", "123");
list.add(jsonObject);
String s = new String(SerializationUtils.serialize(list));
System.out.println(s);
System.out.println(SerializationUtils.deserialize(s.getBytes()));
}
}
打印结果:
�� sr java.util.ArrayListx����a� I sizexp w sr com.alibaba.fastjson.JSONObject L mapt Ljava/util/Map;xpsr java.util.HashMap���`� F
loadFactorI thresholdxp?@ t at 123xx
Exception in thread "main" java.lang.IllegalArgumentException: Failed to deserialize object
at org.springframework.util.SerializationUtils.deserialize(SerializationUtils.java:72)
at demo.TempTest.main(TempTest.java:17)
Caused by: java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
at org.springframework.util.SerializationUtils.deserialize(SerializationUtils.java:68)
... 1 more
问题原因:
暂未弄清,欢迎大佬指点
解决方案:
使用Base64编码、解码的方式解决
关于Base64可以参考:https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576
代码如下:
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.SerializationUtils;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
public class TempTest {
public static void main(String[] args) {
List<JSONObject> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("a", "123");
list.add(jsonObject);
// 使用Base64编码
String s = Base64.getEncoder().encodeToString(SerializationUtils.serialize(list));
System.out.println(s);
// 使用Base64解码
System.out.println(SerializationUtils.deserialize(Base64.getDecoder().decode(s)));
}
}
打印结果:
rO0ABXNyABNqYXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAABdwQAAAABc3IAH2NvbS5hbGliYWJhLmZhc3Rqc29uLkpTT05PYmplY3QAAAAAAAAAAQIAAUwAA21hcHQAD0xqYXZhL3V0aWwvTWFwO3hwc3IAEWphdmEudXRpbC5IYXNoTWFwBQfawcMWYNEDAAJGAApsb2FkRmFjdG9ySQAJdGhyZXNob2xkeHA/QAAAAAAADHcIAAAAEAAAAAF0AAFhdAADMTIzeHg=
[{"a":"123"}]