1. Android JSON解析简单实现,JSON内容如下:
private static final String jsonStr = "{\n" + " \"contacts\": [\n" + " {\n" + " \"id\": \"c200\",\n" + " \"name\": \"Ravi Tamada\",\n" + " \"email\": \"ravi@gmail.com\",\n" + " \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" + " \"gender\" : \"male\",\n" + " \"phone\": {\n" + " \"mobile\": \"+91 0000000000\",\n" + " \"home\": \"00 000000\",\n" + " \"office\": \"00 000000\"\n" + " }\n" + " },\n" + " {\n" + " \"id\": \"c201\",\n" + " \"name\": \"Johnny Depp\",\n" + " \"email\": \"johnny_depp@gmail.com\",\n" + " \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" + " \"gender\" : \"male\",\n" + " \"phone\": {\n" + " \"mobile\": \"+91 0000000000\",\n" + " \"home\": \"00 000000\",\n" + " \"office\": \"00 000000\"\n" + " }\n" + " },\n" + " ]\n" + "}";
private List<Map<String, String>> jsonList = new ArrayList<Map<String, String>>();
try { JSONObject jsonObject = new JSONObject(jsonStr); // JSONArray节点 JSONArray jsonArray = jsonObject.getJSONArray("contacts"); // 循环获取contacts每个内容 for (int i = 0; i < jsonArray.length(); i++) { JSONObject c = jsonArray.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone 节点表示一个JSONObject JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // 把contact放到map Map<String, String> contactMap = new HashMap<String, String>(); contactMap.put("id", id); contactMap.put("name", name); contactMap.put("email", email); contactMap.put("mobile", mobile); contactMap.put("address", address); contactMap.put("gender", gender); contactMap.put("home", home); contactMap.put("office", office); // 把map放到list jsonList.add(contactMap); } } catch (Exception e) { e.printStackTrace(); } |