【问题标题】:How do i match the key from api with another key from the same api, under same object?如何将来自 api 的密钥与来自同一 api 的另一个密钥在同一对象下匹配?
【发布时间】:2017-02-14 22:29:33
【问题描述】:

我正在构建一个 android 应用测验,我正在学习如何从 API 获取数据并显示它。 到目前为止,我做得很好。但我似乎无法走得更远。 我使用的免费api是这个

https://www.opentdb.com/api.php?amount=10&category=10

我的问题是我似乎无法匹配问题和对象的正确答案。我总是在按钮点击时得到随机问题和随机正确答案

这是我的代码

    //url =  https://www.opentdb.com/api.php?amount=25
     public class MainActivity extends AppCompatActivity {


private TextView textData;
private TextView answer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn = (Button) findViewById(R.id.btnId);
    textData = (TextView) findViewById(R.id.txtV);
    answer = (TextView) findViewById(R.id.answerCorrect);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //executing the AsyncTask on button click
            new JSONTask().execute("https://www.opentdb.com/api.php?amount=10&category=10&difficulty=easy&type=multiple");
        }
    });


}
class JSONTask extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        StringBuffer stringBuffer;
        BufferedReader bufferedReader = null;
        try {

            //passing url here

            URL url = new URL(params[0]);
            //making a connection
            connection = (HttpURLConnection) url.openConnection();
            //connecting to the server
            connection.connect();

            //getting object from server and storing to inputStream
            InputStream stream = connection.getInputStream();

            //buffer reader to read the data from inputstream
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            //holding data
            stringBuffer = new StringBuffer();

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {

                stringBuffer.append(line);

            }
            //toString will be passed to the onPostExecute result value
            //return completed JSON object
            String finalOBJ = stringBuffer.toString();
            //passing entire json object in new JSON object instance.
            JSONObject  jsonObject = new JSONObject(finalOBJ);
            //getting the array from the main  object
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            //passing the desired index from the results
            JSONObject fobj = jsonArray.getJSONObject(3);
            JSONObject ansobj = jsonArray.getJSONObject(4);
            //getting the key from results array
            String question = fobj.getString("question");

            return question;
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    //here result will take the data
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        textData.setText(result);
    }
}

我从该站点获取的 JSON APi。

我想要实现的是用来自同一对象的正确答案显示问题。

{
   "response_code":0,
   "results":[
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"easy",
         "question":"George Orwell wrote this book, which is often considered a statement on government oversight.",
         "correct_answer":"1984",
         "incorrect_answers":[
            "The Old Man and the Sea",
            "Catcher and the Rye",
            "To Kill a Mockingbird"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"Which author and poet famously wrote the line, &quot;The female of the species is more deadly than the male&quot;?",
         "correct_answer":"Rudyard Kipling",
         "incorrect_answers":[
            "Edgar Allan Poe",
            "William Shakespeare",
            "William Wordsworth"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the book &quot;The Martian&quot;, how long was Mark Watney trapped on Mars (in Sols)?",
         "correct_answer":"549 Days",
         "incorrect_answers":[
            "765 Days",
            "401 Days",
            "324 Days"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the Harry Potter universe, what is Cornelius Fudge&#039;s middle name?",
         "correct_answer":"Oswald",
         "incorrect_answers":[
            "James",
            "Harold",
            "Christopher"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the Harry Potter universe, who does Draco Malfoy end up marrying?",
         "correct_answer":"Astoria Greengrass",
         "incorrect_answers":[
            "Pansy Parkinson",
            "Millicent Bulstrode",
            "Hermione Granger"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"What is Hermione Granger&#039;s middle name?",
         "correct_answer":"Jean",
         "incorrect_answers":[
            "Jane",
            "Emma",
            "Jo"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"What is Ron Weasley&#039;s middle name?",
         "correct_answer":"Bilius",
         "incorrect_answers":[
            "Arthur",
            "John",
            "Dominic"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"medium",
         "question":"What was the name of the Mysterious Island, in Jules Verne&#039;s &quot;The Mysterious Island&quot;?",
         "correct_answer":"Lincoln Island",
         "incorrect_answers":[
            "Vulcania Island",
            "Prometheus Island",
            "Neptune Island"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"easy",
         "question":"What&#039;s Harry Potter&#039;s dad&#039;s name?",
         "correct_answer":"James Potter",
         "incorrect_answers":[
            "Joey Potter",
            "Frank Potter",
            "Hairy Potter Sr."
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"medium",
         "question":"The book &quot;The Little Prince&quot; was written by...",
         "correct_answer":"Antoine de Saint-Exup&eacute;ry",
         "incorrect_answers":[
            "Miguel de Cervantes Saavedra",
            "Jane Austen",
            "F. Scott Fitzgerald"
         ]
      }
   ]
}

}

【问题讨论】:

    标签: android arrays json api


    【解决方案1】:

    您可以将您的 JSON 数据转换为 Model 类(例如 AttemptItem)对象,然后通过该对象访问它的问题和答案字段。

    查看这个答案How do I convert a JSONObject to class object?

    您可以通过在此处粘贴您的 JSON http://www.jsonschema2pojo.org/ 来获取课程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 2022-12-30
      • 2013-05-12
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      相关资源
      最近更新 更多