[alibaba/fastjson]连续往list添加map,转json出错

2024-09-06 154 views
2

ArrayList<Map<String, Object>> list = new ArrayList<>();

    HashMap<String, Object> map = new HashMap<>();
    map.put("name","张三");
    map.put("age","20");
    list.add(map);
    list.add(map);
    list.add(map);

    String jsonString = JSON.toJSONString(list);
   // [{"name":"张三","age":"20"},{"$ref":"$[0]"},{"$ref":"$[0]"}]
    log.info(jsonString);
    List<Map<String, Object>> list1 = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {
    });
    Map<String, Object> map2 = list1.get(1);
    for (Map.Entry<String, Object> requestParam : map2.entrySet()) {
        // key:$ref value:$[0]
        log.info("key:"+requestParam.getKey()+" value:"+requestParam.getValue());
    }

回答

4

你的期望是?这个么?"name":"张三","age":"20"

5

你的期望是?这个么?"name":"张三","age":"20"

5

String jsonString = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);

关闭引用检查,就可以实现你的效果。但是可能会引起异常。