JSONObject 序列化后,对象数据为引用地址

最近在json序列化的时候,遇到了个坑,记录如下:

public static void main(String[] args) {
		JSONObject json = new JSONObject();
		JSONArray temp = new JSONArray();
		temp.add("t");
		temp.add("q");
		json.put("tm", temp);

		JSONObject result = new JSONObject();
		result.put("v1", json);
		result.put("v2", json);

		System.out.println(result.toJSONString());
	}

执行结果为:

原因:json序列化后,相同的对象只是做了个指向,因此导致了数据结果和原先设想的不一样。

解决方式:走深拷贝处理相同对象,令其在内存中为一个新开的内存地址。

 

posted @ 2019-04-21 15:03  温柔了十里春冬  阅读(1595)  评论(0编辑  收藏  举报