json轉換遇到的問題(JSONObject.toJSONString的問題)


問題:
Stirng數據放入map中,再取出來是一個object,轉換成String后,使用jsonObject.parseObject(),轉換報了異常:com.alibaba.fastjson.JSONException: syntax error, expect {, actual string, pos 83, line 1,
解決方案:

  1. 使用object.toString();來轉換成String,不要使用JSONObject.toJSONString();
  2. Object parse = JSONObject.parse(newStr);
    Map<String,String> map2 = JSONObject.parseObject(parse.toString(), HashMap.class);
    

完整代碼demo

public static void main(String[] args) {
        String str = "{\"key\":\"{\\\"childKey1\\\":\\\"value1\\\",\\\"childKey2\\\":\\\"value2\\\"}\"}";
        Map<String,String> newMap = JSONObject.parseObject(str, HashMap.class);
        System.out.println("newMap = " + newMap);
        Object oldObj = str;
        Map<String, Object> map = new HashMap();
        map.put("1",oldObj);
        Object newObj = map.get("1");
        // ----------------------------解決方案一
        String newStr = newObj.toString();
        String newStr1 = JSONObject.toJSONString(newObj);
        System.out.println("newStr = " + newStr);
        System.out.println("newStr1 = " + newStr1);

        // -----------------------第一種轉換方法 報異常-----------------------------
        Map<String,String> newMap1 = JSONObject.parseObject(newStr, HashMap.class);
        System.out.println("newMap1 = " + newMap1);

        // ------------------------解決方案二 不報異常的--------------------------------
        Object parse = JSONObject.parse(newStr);
        Map<String,String> map2 = JSONObject.parseObject(parse.toString(), HashMap.class);
        System.out.println("map2 = " + map2);
}

image
image
注意:可以看出fastjson的toJsonString方法不是能得到自己想要的結果。它不會去除轉義字符!實際上兩種解決方案都是用的Object.toString();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM