Extract a string from a JSONArray

问题: I'm trying to build a Quiz game for fun but I'm struggling to figure out how to pull the string I want from a JSONArray in Android Studio I'm getting the Log of the "JSON...

问题:

I'm trying to build a Quiz game for fun but I'm struggling to figure out how to pull the string I want from a JSONArray in Android Studio

I'm getting the Log of the "JSON" and "results" come up in Logcat but I can't seem to work out how to set my mQuestion variable to the relevant string.

The JSON

{
"response_code":0,
"results":[{
    "category":"General Knowledge",
    "type":"multiple",
    "difficulty":"medium",
    "question":"According to the BBPA, what is the most common pub name in the UK?",
    "correct_answer":"Red Lion",
    "incorrect_answers": [ 
        "Royal Oak",
        "White Hart",
        "King's Head"
     ]
}]
}

My code

@Override
protected void onPostExecute(String s) {
   super.onPostExecute(s);
   Log.i("JSON", s);

   try {
        JSONObject jsonObject = new JSONObject(s);
        String results = jsonObject.getString("results");
        Log.i("results", results);
        JSONArray arr = new JSONArray(results);
        for (int i = 0; i < arr.length(); i++) {
            mQuestion = arr.getJSONObject(3).getString("question");

            Log.i("Question", mQuestion);
        }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

I get in the Logcat is W/System.err: at ...MainActivity$getQuestion.onPostExecute(MainActivity.java:67)

67 is the line containing "mQuestion = arr.getJSONObject(3).getString("question");"


回答1:

You need to use i you declare in loop:

  mQuestion = arr.getJSONObject(i).getString("question");

回答2:

You are parsing JsonObject and JsonArray wrongly. use this code:

 @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Log.i("JSON", s);

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONArray results = jsonObject.getJSONArray("results");
                    JSONObject jsonObject1 = results.getJSONObject(0);
                    Log.i("results", results.toString());
                    String mQuestion = jsonObject1.getString("question");
                    Log.i("Question", mQuestion);

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
  • 发表于 2019-01-16 03:14
  • 阅读 ( 227 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除