这是我的JSON文件:
[
{"frag1":
[
{"Title":"hello this is first fragment"},
{"SubTitle":"Hello"},
{"photo":"http://edition.cnn.com/2016/08/01/sport/refugee-runners-kenya-mckenzie/index.html"}
]},
{"frag2":
[
{"Title":"hello this is second fragment"},
{"SubTitle":"Hi"},
{"About":"this is the about"}
]}
]
我正在使用此方法从assets文件夹中读取JSON文件:
public String loadJSONFromAsset() {
String json;
try {
InputStream is = getApplication().getAssets().open("json.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
我想将这个JSON分成两部分并将其放入列表中, 所以list1 [0]将包含“Title”,list1 [1]将包含“SubTitle”,list1 [2]将包含“photo”。 当然,与JSON第二部分相同的list2。
更新
所以,这就是我提出的,请建议更好的方法来实现这一点,我正在寻找一种更通用的方式,我的意思是没有像这里写“标题”:listFrag1.add(jsonArrayFrag1.getJSONObject(0).getString("Title"));
假设我不知道对象的名字是什么,是否可能?
public void handleJSON() {
ArrayList listFrag1Frag2 = new ArrayList();
try {
JSONArray fullJson = new JSONArray(loadJSONFromAsset());
for (int i = 0; i < fullJson.length(); i++) {
listFrag1Frag2.add(fullJson.getString(i)); //splits the original json into 2 objects, frag1 and frag2
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
//getting first part of json: frag1: title, subtitle and photo
ArrayList listFrag1 = new ArrayList();
JSONObject objectFrag1 = new JSONObject(listFrag1Frag2.get(0).toString());
JSONArray jsonArrayFrag1 = objectFrag1.getJSONArray("frag1");
listFrag1.add(jsonArrayFrag1.getJSONObject(0).getString("Title"));
listFrag1.add(jsonArrayFrag1.getJSONObject(1).getString("SubTitle"));
listFrag1.add(jsonArrayFrag1.getJSONObject(2).getString("Photo"));
//getting second part of json: frag2: title, subtitle and about
ArrayList listFrag2 = new ArrayList();
JSONObject objectFrag2 = new JSONObject(listFrag1Frag2.get(1).toString());
JSONArray jsonArrayFrag2 = objectFrag2.getJSONArray("frag2");
listFrag2.add(jsonArrayFrag2.getJSONObject(0).getString("Title"));
listFrag2.add(jsonArrayFrag2.getJSONObject(1).getString("SubTitle"));
listFrag2.add(jsonArrayFrag2.getJSONObject(2).getString("About"));
} catch (JSONException e) {
e.printStackTrace();
}
}