2013-12-13 51 views
0

如何在android中创建JSON文件? 我想创建这种看起来像JSON。android动态创建和编辑JSON

{ 
"contacts": [ 
    { 
      "id": "c200", 
      "name": "Ravi Tamada", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 

    }, 
    { 
      "id": "c201", 
      "name": "Johnny Depp", 
      "email": "[email protected]", 
      "address": "xx-xx-xxxx,x - street, x - country", 
      "gender" : "male", 

    }, 
    . 
    . 
    . 
    . 

] }

嗯,我可以创造一个JSONObjects,但无法弄清楚如何包装,在 “联系人” 阵列。

JSONObject json = new JSONObject(); 
try { 
    json.put("id", dataList.get(pos).id); 
    json.put("name", dataList.get(pos).name); 
    . 
    . 
    . 
String jsonString = json.toString(); 
//and then save it 
FileOutputStream fos = mContext.openFileOutput("jsonfile", Context.MODE_PRIVATE); 
        fos.write(jsonString.getBytes()); 
        fos.close(); 

当我会读回JSON,我可以编辑JSON,就像从中间删除的JSONObject,末等添加新的项目?

回答

0

使用jsonarray使用JSONArray array并把对象数组像你这样做是在 的JSONObject

JSONObject json = new JSONObject(); 
    JSONArray array = new JSONArray(); 
    try { 
     json.put("id", dataList.get(pos).id); 
     json.put("name", dataList.get(pos).name); 

    array.put("contacts", json);