Java中输出Json带有转义字符

Java中输出Json带有转义字符

    
    @ResponseBody
    @PostMapping("/test")
    public String test(@RequestBody User user) throws JSONException {

        JSONObject jsonObject=new JSONObject();
          jsonObject.put("name1", "张三1");
          jsonObject.put("age1", 221);
          jsonObject.put("name2", "张三2");
          jsonObject.put("age2", 222);
          jsonObject.put("name3", "张三3");
          jsonObject.put("age3", 223);
          jsonObject.put("name4", "张三4");
          jsonObject.put("age4", 224);

        String str = jsonObject.toString();
        System.out.println(str);

        String str1 = str.replace("\"" , "\\\"");  //单斜杆
        System.out.println(str1);

        String str2 = str.replace("\"","\\\\\"");  //双斜杆
        System.out.println(str2);

        return str2;
        
    }
    

输出


{"name4":"张三4","name3":"张三3","age4":224,"age3":223,"name2":"张三2","name1":"张三1","age2":222,"age1":221}

{\"name4\":\"张三4\",\"name3\":\"张三3\",\"age4\":224,\"age3\":223,\"name2\":\"张三2\",\"name1\":\"张三1\",\"age2\":222,\"age1\":221}

{\\"name4\\":\\"张三4\\",\\"name3\\":\\"张三3\\",\\"age4\\":224,\\"age3\\":223,\\"name2\\":\\"张三2\\",\\"name1\\":\\"张三1\\",\\"age2\\":222,\\"age1\\":221}

你可能感兴趣的:(Java)