【问题标题】:How to get Json Array Content to ArrayList<String> in Java?如何在 Java 中将 Json 数组内容获取到 ArrayList<String>?
【发布时间】:2015-07-11 07:19:28
【问题描述】:
我在 android“资产”文件夹中有 Json 文件。 Json 文件有五个以上的数组,如何存入 Java ArrayList 或如何将 Json Array 直接获取到 forLoop。
【问题讨论】:
标签:
android
arrays
json
arraylist
【解决方案1】:
试试这个方法
public static String AssetJSONFile (String filename, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(filename);
byte[] formArray = new byte[file.available()];
file.read(formArray);
file.close();
return new String(formArray);
}
public void getJson()
{
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
Context context = null;
HashMap<String, String> hashMap;
try {
String jsonLocation = AssetJSONFile("yourjson.json", context);
String id;
String question;
JSONArray JsonArray = jsonObject.getJSONArray("arjuna");
{
for (int k = 0; k < JsonArray.length(); k++)
{
JSONObject jsonObject = JsonArray.getJSONObject(k);
id= JSONObject.getString("id");
question= JSONObject.getString("question");
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("question", question);
formList.add(hashMap);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
【解决方案2】:
try {
InputStream inputStream = getAssets().open("json.txt");
String s = convertStreamToString(inputStream);
JSONObject object = new JSONObject();
JSONArray jsonArray = object.getJSONArray("arjuna");
HashMap hashMap = null;
ArrayList<HashMap> arrayList = new ArrayList<HashMap>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
int id = obj.getInt("id");
String question = obj.getString("question");
hashMap = new HashMap();
hashMap.put("id", id);
hashMap.put("question", question);
arrayList.add(hashMap);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}