如何解决JSONObject序列化与Map序列化结果不一致的问题?-灵析社区

M78的社畜

采用net.sf.json.JSONObject处理数据时,type字段序列化后能不能和采用Map处理数据时输出的结果一致呢? @Test public void testJsonObject() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); List type = Lists.newArrayList("A", "B"); JSONObject jsonObject = new JSONObject(); jsonObject.put("type", objectMapper.writeValueAsString(type)); System.out.println(objectMapper.writeValueAsString(jsonObject)); Map 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可以直接反序列化为字符串数组,但是序列化两次的不能直接反序列化为字符串数组

阅读量:161

点赞量:0

问AI
实在没找到这个"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" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20240927/e2eb64cc301b6131ddbdd5fe31134781.png)