json字符串转义格式化后再转换处理demo StringEscapeUtils.unescapeJava
报错关键字:
illegal identifier
Expected BEGIN_OBJECT but
Expected name at
package com.example.core.mydemo; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.apache.commons.lang3.StringEscapeUtils; import java.util.Map; /** * json字符串转义格式化后再转换处理demo * 转义的问题。 * 在读取到这个json字符串之后,发现该字符串中包含了\转义符号,程序自动把它变成了\\\ * 如果遇到类似的问题,可以直接使用org.apache.commons包下的StringEscapeUtils类,先去掉转义,再反序列化,这样可以快速解决问题。 * */ public class json6 { public static void main(String[] args) { String json = "{\\\"accountNonExpired\\\":true,\\\"accountNonLocked\\\":true,\\\"authorities\\\":[{\\\"authority\\\":\\\"admin\\\"}],\\\"credentialsNonExpired\\\":true,\\\"enabled\\\":true,\\\"id\\\":13,\\\"password\\\":\\\"$2a$10$o3XfeGr0SHStAwLuJRW6y.kE0UTerQfv3SXrAcVLuJ6M3hEsC9RKe\\\",\\\"roles\\\":[\\\"admin\\\"],\\\"username\\\":\\\"admin\\\"}"; //case1 fastjson // Map map = JSON.parseObject(json, Map.class); /** * 报错信息:com.alibaba.fastjson.JSONException: illegal identifier : \pos 1, line 1, column 2 */ // System.out.println("map="+map); //转换成功 // json = StringEscapeUtils.unescapeJava(json); // Map map2 = JSON.parseObject(json, Map.class); // System.out.println("map2="+map2); //case2 jackson // ObjectMapper objectMapper = new ObjectMapper(); // try { // //加上这行,不报错。 // json = StringEscapeUtils.unescapeJava(json); // // Map map = objectMapper.readValue(json, Map.class); // /** // * 报错信息:com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\' (code 92)): was expecting double-quote to start field name // */ // System.out.println("map="+map); // } catch (JsonProcessingException e) { // e.printStackTrace(); // } //case3 gson json = StringEscapeUtils.unescapeJava(json); Map map3 = new Gson().fromJson(json, Map.class); /** * 报错信息:com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $. */ System.out.println("map3="+map3); } }
标签:Map,unescapeJava,demo,json,com,import,StringEscapeUtils From: https://www.cnblogs.com/oktokeep/p/18401706