json 取出之問題
{"contents":[{"productID":34,"productName":"SuperWidget"},{"productID":56,"productName":"WonderWidget"}]}
private void saveFile() {
try {
FileOutputStream fileOutputStream = openFileOutput("123.txt",
Context.MODE_PRIVATE);
fileOutputStream.write(resource.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JSONExampleActivity.this, "儲存成功", Toast.LENGTH_LONG).show();
}
private void readFile() {
String temp = null;
try {
FileInputStream fileInputStream = openFileInput("123.txt");
int length = fileInputStream.available();
byte[] buffer = new byte[length];
fileInputStream.read(buffer);
fileInputStream.close();
temp = new String(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
[解决办法]
JSONArray array = new JSONArray(temp);
for(int i=0;i<array.size();i++){
JSONObject obj = array.get(i);
String str = obj.getString("productID");
}