如何遍历这个JSON对象中的所有"listPages“?
{
"listPages": [
{
"title": "Accounts",
"recordType": "Company",
},
{
"title": "Contacts",
"recordType": "Person",
}
]
}我尝试通过以下代码从listPages数组中的每一项中将列表项添加到列表中:
JSONObject JSONConfig = envConfig.getEnvConfig(this);
try{
JSONArray listPages = JSONConfig.getJSONArray("listPages");
for(int i = 0 ; i < listPages.length() ; i++){
listItems.add(listPages.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();
}catch(Exception e){
e.printStackTrace();
}我可以在logcat中看到下面一行出现系统错误:"java.lang.NullPointerException“。
JSONArray listPages = JSONConfig.getJSONArray("listPages");我试着阅读和调整其他问题的内容,但我不能弄明白。如果能帮上忙,我们将不胜感激。
这是我的envConfig.java类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class EnvConfig {
private String rawJSONString;
private JSONObject jsonObjRecv;
public JSONObject getEnvConfig(Context context){
InputStream inputStream = context.getResources().openRawResource(
R.raw.envconfigg);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
rawJSONString = sb.toString();
try {
JSONObject jsonObjRecv = new JSONObject(rawJSONString);
Log.i("Test", "<JSONObject>\n" + jsonObjRecv.toString()
+ "\n</JSONObject>");
} catch (Exception e) {
e.printStackTrace();
}
return jsonObjRecv;
}
}发布于 2013-03-06 11:12:30
这是一个经典的实例阴影问题。您可以在try块的方法中声明一个新变量,并使用与类变量相同的名称。因此,类变量被屏蔽,因此永远不会被初始化。当您稍后从该方法返回它时,它为空。
public class EnvConfig {
private String rawJSONString;
private JSONObject jsonObjRecv; // <-- you declare a class variable here
// ...
try {
JSONObject jsonObjRecv = new JSONObject(rawJSONString); // <-- shadowed here!除非您试图避免重复地重新解析JSON,否则我建议您完全去掉类变量。否则,去掉局部变量。
发布于 2013-03-06 10:09:09
这是我用来解析我的JSON数据的代码,我不熟悉您正在使用的JSONConfig,但是它对我来说工作得很好。
JSONObject jsonObject = (JSONObject) new JSONTokener(/*Json String Data*/).nextValue();
JSONArray jsonArray = jsonObject.getJSONArray(/*Name of JSON Array*/);https://stackoverflow.com/questions/15237658
复制相似问题