(1)JAVA對象序列化方法
/** * 將JAVA對象序列化為JSON字符串 */ public String serializeJson(Object obj) throws IOException { String _json = new Gson().toJson(obj); return _json; }
(2)JAVA對象反序列化方法
/** * 將JSON字符串反序列化為JAVA對象 */ public <T> T deserializeJson(String json, Class<T> cla) throws JsonParseException, IOException { Gson gson = new Gson(); return gson.fromJson(json, cla); }
(3)反序列化List<Object>
/** * 將JSON字符串反序列化為JAVA對象集合 * @param <T> */ public <T> List<T> deserializeListJson(String json, Class<T> cla) throws JsonParseException, IOException { Gson gson = new Gson(); @SuppressWarnings({ "unchecked", "rawtypes" }) List<LinkedTreeMap> list = gson.fromJson(json, List.class); List<T> result = new ArrayList<>(); if(list!=null && list.size()>0){ for (@SuppressWarnings("rawtypes") LinkedTreeMap item : list) { result.add(JsonUtils.getInstance().deserializeJson(JsonUtils.getInstance().serializeJson(item),cla)); } } return result; }
之前一直使用的(2)中的方法,但是那樣反序列化出來的List對象在遍歷的時候會出錯:
import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.JsonParseException; import com.googosoft.model.MessageBeans; import com.googosoft.util.JsonUtils; /** * @author songyan * @date 2020年6月3日 上午8:06:40 * @desc 序列化反序列化測試類 */ public class JsonTest { public static void main(String[] args) throws JsonParseException, IOException { //封裝測試數據 List<MessageBeans> messageBeansList = new ArrayList<>(); for (int i = 0; i <3; i++) { MessageBeans messageBeans = new MessageBeans(); messageBeans.setCommand("command"+(i+1)); messageBeansList.add(messageBeans); } //序列化反序列化 JsonUtils jsonUtils = JsonUtils.getInstance(); @SuppressWarnings("unchecked") List<MessageBeans> list = jsonUtils.deserializeJson(jsonUtils.serializeJson(messageBeansList), List.class); for (MessageBeans messageBeans : list) { System.out.println(messageBeans); } } }
反序列化List<Object>對象的正確姿勢:
//序列化反序列化 JsonUtils jsonUtils = JsonUtils.getInstance(); List<MessageBeans> list = jsonUtils.deserializeListJson(jsonUtils.serializeJson(messageBeansList), MessageBeans.class); for (MessageBeans messageBeans : list) { System.out.println(messageBeans); }
關於LinkedTreeMap:https://www.jianshu.com/p/bd650eb62ca5