如何解决JSONObject序列化与Map序列化结果不一致的问题?

新手上路,请多包涵

采用net.sf.json.JSONObject处理数据时,type字段序列化后能不能和采用Map处理数据时输出的结果一致呢?

@Test
    public void testJsonObject() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> type = Lists.newArrayList("A", "B");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", objectMapper.writeValueAsString(type));
        System.out.println(objectMapper.writeValueAsString(jsonObject));


        Map<String, Object> map = new HashMap<>();
        map.put("type", objectMapper.writeValueAsString(type));
        System.out.println(objectMapper.writeValueAsString(map));
    }

输出

{"type":["A","B"]}
{"type":"[\"A\",\"B\"]"}

序列化两次type

jsonObject.put("type", objectMapper.writeValueAsString(objectMapper.writeValueAsString(type)));

输出

{"type":"[\\\"A\\\",\\\"B\\\"]"}
{"type":"[\"A\",\"B\"]"}

输出与采用Map还是不同,Map输出的type可以直接反序列化为字符串数组,但是序列化两次的不能直接反序列化为字符串数组

阅读 1.1k
2 个回答

实在没找到这个net.sf.json.JSONObject

JSONObject jsonObject = new JSONObject();
jsonObject.put("type", objectMapper.writeValueAsString(type));

// FIXME: <猜测> 问题在这里 jsonObject 本身就是JSON对象,理论上 jsonObject.asString()? 类似的方法应该有,直接转为String类型
System.out.println(objectMapper.writeValueAsString(jsonObject));

建议你换个JSON类库。

image.png

新手上路,请多包涵

相同代码使用net.minidev.json.JSONObject,输出的结果是一致的:

{"type":"[\"A\",\"B\"]"}
{"type":"[\"A\",\"B\"]"}

或许你可以考虑换个json库。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题