[英]How to parse json response in android which is of the following format
I am trying to parse a json response in android for my android application. 我试图在我的android应用程序中解析android中的json响应。 I am getting
org.json.JSONException
. 我收到
org.json.JSONException
。 The response is as shown below: 响应如下所示:
{
id: "12345"
email:"abc@gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
I am trying to parse the response as shown below: 我正在尝试解析响应,如下所示:
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();
}
Can any one let me know what mistake am I doing in parsing the response. 任何人都可以让我知道我在解析响应时犯了什么错误。 All suggestions are welcome.
欢迎所有建议。
Simply replace this you are using "_id" instead of "id" 简单地替换它你使用“_id”而不是“id”
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
Change this id = c.getString("_id");
更改此
id = c.getString("_id");
to id = c.getString("id");
to
id = c.getString("id");
in the future, you may show error in logcat when parsing like this: 将来,在解析时可能会在logcat中显示错误:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
There are two things I can think of , first of all you should get to know that what are [] , {} . 我可以想到两件事,首先你应该知道什么是[],{}。 The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong
方括号是json中的数组,并且卷曲演示了对象,所以我认为你错了
1> 1>
JSONArray contacts = new JSONArray(response.toString());
JSONArray contacts = new JSONArray(response.toString()); "this is culprit"
“这是罪魁祸首”
You should change it to 你应该把它改成
JSONObject.
JSONObject的。 Use JSONObject in place of JSONArray
使用JSONObject代替JSONArray
and Secondly 其次
2> change this key id = c.getString("_id");to 2>更改此密钥id = c.getString(“_ id”); to
id = c.getString("id");
id = c.getString(“id”);
Make sure You are getting and writing spellings of all keys right else it would generate exception. 确保你正在获取和编写所有键的拼写,否则它将产生异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.