第一种方法:
String str = "{'array':[{'id':5,'name':'张三'},{'id':6,'name':'李四'}]}"; JSONArray jsonArray = null; jsonArray = jsonobj.getJSONArray("array");//获取数组 System.out.println(jsonArray.getJSONObject(0).get("name"));
String str = "[{'columnId':5,'columnName':'人文历史'},{'columnId':2,'columnName':'商业视野'}]}"; JSONArray jsonArray = null; jsonArray = new JSONArray(str); System.out.println(jsonArray.getJSONObject(0).get("columnName"));
二、JAVA获取json中的全部键值对
JSONObject json1=JSONObject.fromObject("{'username' : '11111','clientid' : '','password' : '222222'}"); Map<String, Object> map =json1; for (Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey()+"="+entry.getValue()); }
三提取json中某个数组的所有值
public class JsonExtracter { public static void main(String[] args) { String s = "{\"name\":\"a\",\"family\":[\"张三\",\"李四\"]}"; JSONObject jsonObject = JSON.parseObject(s); //注意:family中的内容带有中括号[],所以要转化为JSONArray类型的对象 JSONArray family = jsonObject.getJSONArray("family"); for (int i = 0; i < family.size(); i++) { //提取出family中的所有 String s1 = (String) family.get(i); System.out.println("currentFamily:" + s1); } }