这次做接口时,对方把图片类型和图片地址用的是数组,所有我需要用JSONArray做拼接,使用的过程中出现了{"$ref":"$.certPicInfos[0]"}异常。
public void test3() { JSONObject json = new JSONObject(); String picUrls = "1|test1.png;2|test2.png"; JSONArray jsonArr = new JSONArray(); String[] certPicUrls = picUrls.split(";"); JSONObject para = new JSONObject();//出错代码 for (String certPicUrl : certPicUrls) { String picKey = certPicUrl.substring(0, certPicUrl.indexOf("|")); String picValue = certPicUrl.substring(certPicUrl.indexOf("|") + 1, certPicUrl.length()); para.put("certPicType", picKey); para.put("certPicUrl", picValue); jsonArr.add(para); } json.put("certPicInfos", jsonArr); System.out.println(json); }
|
出错原因:JSONObject对象被引用了两次。
解决方法:将JSONObject的创建放到循环体内
public void test3() {
JSONObject json = new JSONObject(); String picUrls = "1|test1.png;2|test2.png"; JSONArray jsonArr = new JSONArray(); String[] certPicUrls = picUrls.split(";"); JSONObject para = new JSONObject(); for (String certPicUrl : certPicUrls) {
JSONObject para = new JSONObject();//正确代码
String picKey = certPicUrl.substring(0, certPicUrl.indexOf("|")); String picValue = certPicUrl.substring(certPicUrl.indexOf("|") + 1, certPicUrl.length()); para.put("certPicType", picKey); para.put("certPicUrl", picValue); jsonArr.add(para); } json.put("certPicInfos", jsonArr); System.out.println(json); }
|