第一種(java8):遍歷JSONArray 拼接字符串java
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循環遍歷json
public static void f2(JSONArray ja) { for(int i=0;i<ja.size();i++) { System.out.println(ja.getJSONObject(i).get("id")); } }