-2
我有Android的“资产”文件夹中的Json文件。 Json文件有五个以上的数组如何存储到Java ArrayList中,或者如何直接将Json数组存储到forLoop中。如何在Java中将Json Array内容获取到ArrayList <String>?
我有Android的“资产”文件夹中的Json文件。 Json文件有五个以上的数组如何存储到Java ArrayList中,或者如何直接将Json数组存储到forLoop中。如何在Java中将Json Array内容获取到ArrayList <String>?
尝试这种方式
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();
}
}
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();
}
你尝试的东西?把这个放在这里。 – Rustam
像随机问题生成从Json数组在TextView中 – sabish
把你的JSON数据 –