[英]How to parse json response in android which is of the following format
我试图在我的android应用程序中解析android中的json响应。 我收到org.json.JSONException
。 响应如下所示:
{
id: "12345"
email:"abc@gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
我正在尝试解析响应,如下所示:
if (response != null) {
try {
//JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray contacts = new JSONArray(response.toString());
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
id = c.getString("_id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
}
} catch (JSONException e) {
e.printStackTrace();
}
任何人都可以让我知道我在解析响应时犯了什么错误。 欢迎所有建议。
简单地替换它你使用“_id”而不是“id”
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
更改此id = c.getString("_id");
to id = c.getString("id");
将来,在解析时可能会在logcat中显示错误:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
我可以想到两件事,首先你应该知道什么是[],{}。 方括号是json中的数组,并且卷曲演示了对象,所以我认为你错了
1>
JSONArray contacts = new JSONArray(response.toString()); “这是罪魁祸首”
你应该把它改成
JSONObject的。 使用JSONObject代替JSONArray
其次
2>更改此密钥id = c.getString(“_ id”); to
id = c.getString(“id”);
确保你正在获取和编写所有键的拼写,否则它将产生异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.