第一种(java8):遍历JSONArray 拼接字符串
public static void main(String[] args) { JSONArray jSONArray = new JSONArray(); JSONObject jb = new JSONObject(); jb.put("id", 1); jb.put("name", "s"); jSONArray.add(jb); JSONObject j1 = new JSONObject(); j1.put("id", 2); j1.put("name", "s"); jSONArray.add(j1); StringBuffer sBuffer = new StringBuffer(); jSONArray.stream().forEach(jsonobejct->arrayIdToString((JSONObject) jsonobejct,sBuffer)); System.out.println(sBuffer.toString()); } private static StringBuffer arrayIdToString(JSONObject jsonobejct, StringBuffer sBuffer) { return sBuffer.append(jsonobejct.getInteger("id")).append(","); }
第二种:for循环遍历
public static void f2(JSONArray ja) { for(int i=0;i<ja.size();i++) { System.out.println(ja.getJSONObject(i).get("id")); } }