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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM