创建JSON数据:
public class CreateJson { public static Object createJson(){ // 首先最外层是{},是创建一个对象 JSONObject jsonObject = new JSONObject(); // 第一个键contact的值是数组,所以需要创建数组对象 JSONArray contactArray = new JSONArray(); try { for (int i=0;i<9;i++) { // contact数组里有9个object,所以要创建对象 JSONObject contactJsonObject = new JSONObject(); contactJsonObject.put("name", "张三"+i); contactJsonObject.put("phone", "1785352000"+i); contactArray.put(contactJsonObject); } jsonObject.put("contact",contactArray); return jsonObject; } catch (JSONException e) { e.printStackTrace(); return null; } } }
解析JSON数据:
private void readJson(){ jsonString = CreateJson.createJson().toString(); try { JSONObject jsonObject = new JSONObject(jsonString); contact = jsonObject.getJSONArray("contact"); for (int i=0;i<contact.length();i++){ JSONObject contactObject = contact.getJSONObject(i); String name = contactObject.getString("name"); String phone = contactObject.getString("phone"); names.add(name); phones.add(phone); } } catch (JSONException e) { e.printStackTrace(); } }
JSON数据:
{ "contact": [ { "name": "张三0", "phone": "17853520000" }, { "name": "张三1", "phone": "17853520001" }, { "name": "张三2", "phone": "17853520002" }, { "name": "张三3", "phone": "17853520003" }, { "name": "张三4", "phone": "17853520004" }, { "name": "张三5", "phone": "17853520005" }, { "name": "张三6", "phone": "17853520006" }, { "name": "张三7", "phone": "17853520007" }, { "name": "张三8", "phone": "17853520008" } ], "fff": { "name": 1, "phone": "17853520000" } }
json数据格式:
JSON数据: 一对 {}代表一个JSONObject,第一个大括号用new JSONObject( String Json ) 得到一个jsonObject,一对[ ] 代表JSONArray. 解析JSONObject用jsonobject.getJSONObject( String key )方法,解析JSONArray调用jsonobject.getJsonArray(String key);
此后解析方法基本一样.