如果我有像这样的json文件
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name ": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
},
]}
如何读取这个json文件并将所有名称放在android
中的String数组中我使用了这段代码但是在第二个循环中它捕获了异常
public void loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.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();
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("users");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
names.add(jo_inside.getString("name"));
images.add(jo_inside.getString("address"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
数组中Json对象的第二个元素在名称旁边有空格,您可以通过2种方式解决。
将getString更改为optString,如下所示
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name = jo_inside.optString("name");
if(TextUtils.isEmpty(name)) {
name = jo_inside.optString("name "); // that object have space
}
names.add(name);
images.add(jo_inside.getString("address"));
}
答案 1 :(得分:1)
您的Json
文件包含格式错误的JSON。
从最后一个数组元素中删除,
{
"name": "cc",
"address": "c"
},
有效的Json应该是:
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
}
]
}
答案 2 :(得分:1)
您的JSON字符串中只有问题。在第二个JSON name
字段中有额外的空格。在最后一次JSON ,
},
{
"users": [{
"name":"aa",
"address":"a"
},
{
"name":"bb",
"address":"b"
},
{
"name":"cc",
"address":"c"
}
]
}