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); } }