英文:
JSONException getting the key value
问题
好的,以下是您提供的内容的中文翻译:
我的 "Students" 的 JSON 示例如下所示。
{
"phone":"703-703-1234",
"poc":"XYZ",
"name":"ABC",
"location":"California",
"id":10,
"deletedBy":null,
"statusObj":{
"descr":"IN PROGRESS",
"id":10
},
"createDate":1595396946000,
"deleteDate":null
}
用于获取子元素的代码如下:
JSONArray data = jsonObj.getJSONArray("Students");
for(int i=0; i<data.length(); i++){
if(data.getJSONObject(i).has("statusObj") && !data.getJSONObject(i).isNull("statusObj")){
JSONObject status = (JSONObject)data.getJSONObject(i).get("statusObj");
Iterator iterator = status.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
System.out.println("Descr is ..- "+key);
//JSONObject page = status.getJSONObject(key);
JSONObject page = status.getJSONObject("descr");
System.out.println("Descr is - "+page);
}
}
}
当我尝试获取 "descr" 对象时,出现以下异常:
Descr is ..- descr
org.json.JSONException: JSONObject["descr"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
英文:
My JSON for "Students" looks like the below example.
{
"phone":"703-703-1234",
"poc":"XYZ",
"name":"ABC",
"location":"California",
"id":10,
"deletedBy":null,
"statusObj":{
"descr":"IN PROGRESS",
"id":10},
"createDate":1595396946000,
"deleteDate":null}
My code to get the child elements is this:
JSONArray data = jsonObj.getJSONArray("Students");
for(int i=0; i<data.length(); i++){
if(data.getJSONObject(i).has("statusObj") && !data.getJSONObject(i).isNull("statusObj")){
JSONObject status = (JSONObject)data.getJSONObject(i).get("statusObj");
Iterator iterator = status.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
System.out.println("Descr is ..- "+key);
//JSONObject page = status.getJSONObject(key);
JSONObject page = status.getJSONObject("descr");
System.out.println("Descr is - "+page);
}
}
}
I am getting the following exception when I try to get the "descr" obj
Descr is ..- descr
org.json.JSONException: JSONObject["descr"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
答案1
得分: 1
异常的含义非常明确 - 键"descr"
不是指向一个对象,而是一个字符串。您应该使用getString
代替:
String page = status.getString("descr");
英文:
The exception really says it all - the key "descr"
doesn't refer to an object, but to a string. You should use getString
instead:
String page = status.getString("descr");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论