嗨,我无法从我的PHP的Json输出中解析单个json元素。
我的Json输出看起来像这样。
{"success":1,"question":[{"question":"Question2"}]}
我的代码是
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Questions = json.getJSONArray(TAG_Questions);
Log.d("users_list.length() : ", String.valueOf( Questions.length()));
for (int i = 0; i < Questions.length(); i++)
{
JSONObject c = Questions.getJSONObject(i);
Quensstring[i] = c.getString("question" + i);
System.out.println("Exception : " + Quensstring[i]);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(), day1q1.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
protected void onPostExecute(String file_url)
{
dialog.dismiss();
runOnUiThread(new Runnable()
{
public void run()
{
System.out.println("usersMap.get(User1) : " + Quensstring[0]);
Question.setText(Quensstring[0]);
}
});
请帮助我,我找不到错误。
这是我的日志
09-13 05:46:08.459: D/All :(1353): {"success":1,"question":[{"question":"Question2"}]}
09-13 05:46:08.459: D/users_list.length() :(1353): 1
09-13 05:46:08.499: W/System.err(1353): org.json.JSONException: No value for question0
09-13 05:46:08.499: W/System.err(1353): at org.json.JSONObject.get(JSONObject.java:354)
09-13 05:46:08.539: W/System.err(1353): at org.json.JSONObject.getString(JSONObject.java:510)
09-13 05:46:08.589: W/System.err(1353): at com.example.newairways.day1q1$Question.doInBackground(day1q1.java:474)
09-13 05:46:08.589: W/System.err(1353): at com.example.newairways.day1q1$Question.doInBackground(day1q1.java:1)
09-13 05:46:08.589: W/System.err(1353): at android.os.AsyncTask$2.call(AsyncTask.java:264)
09-13 05:46:08.589: W/System.err(1353): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-13 05:46:08.589: W/System.err(1353): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-13 05:46:08.589: W/System.err(1353): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
09-13 05:46:08.599: W/System.err(1353): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-13 05:46:08.599: W/System.err(1353): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-13 05:46:08.626: W/System.err(1353): at java.lang.Thread.run(Thread.java:856)
09-13 05:46:08.649: I/System.out(1353): usersMap.get(User1) : null
最佳答案
{“成功”:1,“问题”:[{“问题”:“问题2”}]}}。您的JSONArray只有一个JSONObject,而该JSONObject只有1个标记是“ question”。因此,替换您的代码
Quensstring[i] = c.getString("question" + i);
与
String quensString = c.getString("question");
希望这能解决问题。
关于android - android无法解析单个json元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18781622/