JSON对于map重复的Key,转换过程中会报错!具体代码如下,附带报错信息
package com.fjnx.history.collection;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* Description:
* User: xu.debu
* Date: 2020-09-10
* Time: 19:50
*/
public class CollectionTest {
private static final String flag = "\n";
public static void main(String[] args) {
CollectionTest t = new CollectionTest();
t.testOutput();
t.testJsonError();
t.testJsonErrorMethod();
}
/**
* 测试数据展示格式
*/
public void testOutput() {
/**
* 集合及数组以及map,JsonOBjec控制台输出数据格式
*/
int[] array = new int[2];
array[0] = 1;
array[1] = 2;
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", 1);
jsonObject.put("2", 2);
System.out.println(">>>>>>>array " + JSONObject.toJSON(array));
System.out.println(">>>>>>>list " + JSONObject.toJSON(list));
System.out.println(">>>>>>>set " + JSONObject.toJSON(set));
System.out.println(">>>>>>>map " + JSONObject.toJSON(map));
System.out.println(">>>>>>>jsonObject " + jsonObject.toJSONString());
}
/**
* 测试JsonObject对于对象重复的报错信息
*/
public void testJsonError() {
JSONObject jsonObject=new JSONObject();
List<Object> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
Map<String, Object> mapSub1 = new HashMap<>();
mapSub1.put("1",1);
Map<String, Object> mapSub2 = new HashMap<>();
mapSub2.put("1", 2);
map.put("1", mapSub1);
list.add(map);
map.put("1", mapSub2);
list.add(map);
jsonObject.put("jsonObject",list);
System.out.println(">>>>>>>>>JsonData" + JSONObject.toJSON(list));
System.out.println(">>>>>>>>>JsonError" + jsonObject.toJSONString());
}
/**
* 测试JsonObject对于对象重复的报错信息,以下处理方式可以避免报错,
* 就是key相同的map重新赋值之前,重新New个map对象
*/
public void testJsonErrorMethod() {
JSONObject jsonObject=new JSONObject();
List<Object> list = new ArrayList<>();
Map<String, Object> map =null;
Map<String, Object> mapSub1 = new HashMap<>();
mapSub1.put("1",1);
Map<String, Object> mapSub2 = new HashMap<>();
mapSub2.put("1", 2);
map=new HashMap<>();
map.put("1", mapSub1);
list.add(map);
map=new HashMap<>();
map.put("1", mapSub2);
list.add(map);
jsonObject.put("jsonObject",list);
System.out.println(">>>>>>>>>JsonData" + JSONObject.toJSON(list));
System.out.println(">>>>>>>>>testJsonErrorMethod" + jsonObject.toJSONString());
}
}
>>>>>>>map {"1":1,"2":2}
>>>>>>>jsonObject {"1":1,"2":2}
>>>>>>>>>JsonData[{"1":{"1":2}},{"1":{"1":2}}]
>>>>>>>>>JsonError{"jsonObject":[{"1":{"1":2}},{"$ref":"$.jsonObject[0]"}]}
>>>>>>>>>JsonData[{"1":{"1":1}},{"1":{"1":2}}]
>>>>>>>>>testJsonErrorMethod{"jsonObject":[{"1":{"1":1}},{"1":{"1":2}}]}