JSONObject中嵌套json字符串和json对象

1、JSONObject中的String

json串中data对应的值是String,String字符串中双引号需要使用反斜杠\进行转义

{"error_no":"0","error_info":"success!","data":"{\"id\":1,\"name\":\"www\"}"}

代码生成方式

        String str = "{\"id\":1,\"name\":\"www\"}";
        JSONObject jsonStr = new JSONObject(true);
        jsonStr.put("error_no", "0");
        jsonStr.put("error_info", "success!");
        jsonStr.put("data", str);
        System.out.println("字符串放入json串后:"+jsonStr);

2、JSONObject中的Object

json串中data对应的值是对象,解决了前端后端接收时存在双引号和反斜杠的问题

{"error_no":"0","error_info":"success!","data":{"name":"www","id":1}}

代码生成方式

        String str = "{\"id\":1,\"name\":\"www\"}";
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.put("error_no", "0");
        jsonObject.put("error_info", "success!");
        // 将String转换为JSONObject再put
        jsonObject.put("data", JSON.parseObject(str));
        System.out.println("字符串对象放入json串后:"+jsonObject);
posted on 2021-12-09 16:43  cxbks  阅读(2804)  评论(0)    收藏  举报