0

I'm creating a trivia app and familiarizing myself with JSON, but i'm having trouble parsing a JSON object with multiple values to be able to assign each value to a Button.

I have a JSON that looks like this:

{
    "response_code": 0,
    "results": [{
            "question": "question one?",
            "correct_answer": "correct answer",
            "incorrect_answers": ["wrong1", "wrong2", "wrong3"]
        }, {
            "question": "question2",
            "correct_answer": "correct answer",
            "incorrect_answers": ["wrong1", "wrong2", "wrong3"]
        }
    ]
}

I am able to parse "question" and "correct_answer", but am not sure how to go about parsing the incorrect answers.

my Parser:

public class JsonParser
{

private URL urlin;
private static InputStream is = null;
private static JSONObject jObj = null;
private static JSONArray jArray = null;
private String jsonStr = " String to pass back";

public JsonParser()
{
    //empty constructor
}

public JSONObject getJSONfromURL (String url)
{
    HttpURLConnection urlConnection;
    try
    {
        urlin = new URL(url);
        urlConnection = (HttpURLConnection) urlin.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        is.close();
        urlConnection.disconnect();
        jsonStr = sb.toString();

    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            jObj = new JSONObject(jsonStr);
        }
        catch (JSONException je)
        {
            je.printStackTrace();
        }
    }

    return jObj;

}

}

How i'm parsing "question" and "correct_answer":

 myArray = myObj.getJSONArray("results");
 JSONObject tempObj = myArray.getJSONObject(0);
 question = tempObj.getString("question");
 A = tempObj.getString("correct_answer");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Andy
  • 25
  • 8

0 Answers0