[英]Null pointer exception json parsing url android
我正在嘗試從URL中解析一個json條目。 下面是代碼段。
TextView txtViewParsedValue;
private JSONObject jsonObject;
private static String url = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
String strParsedValue = null;
TextView txtViewParsedValue;
private JSONObject jsonObject;
private static String url = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
String strParsedValue = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtViewParsedValue = (TextView) findViewById(R.id.textview1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
JSONParser jParser = new JSONParser();
jsonObject = jParser.getJSONFromUrl(url);
JSONObject object = jsonObject.getJSONObject("student");
JSONArray subArray = object.getJS ONArray("student");
for(int i=0; i<subArray.length(); i++)
{
strParsedValue+="\n"+subArray.getJSONObject(i).getString("id").toString();
}
txtViewParsedValue.setText(strParsedValue);
}
我想提取學生的所有ID,並在textview中打印它們。 它給出了空指針異常。 搜索了一些與此相關的帖子並進行了嘗試,但沒有成功,任何指導都將大有幫助!
student
是JsonArray
而不是JsonObject
但是您正在嘗試將其作為JsonObject
獲得。 將您的解析代碼更改為:
JSONArray subArray =jsonObject.getJSONArray("student");//<<< get student JSONArray
for(int i=0; i<subArray.length(); i++)
{
strParsedValue+=
"\n"+subArray.getJSONObject(i).getString("id").toString();
}
不要使用JSONObject object = jsonObject.getJSONObject("student");
因為根據您的JSON, 學生是一個數組。
更改為
JSONArray subArray = jsonObject.getJSONArray("student");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.