如何解析具有多个值的JSON对象?

时间:2018-02-17 00:48:10

标签: java arrays json android-studio object

我正在创建一个琐事应用程序并熟悉JSON,但我无法解析具有多个值的JSON对象,以便能够将每个值分配给Button。

我有一个看起来像这样的JSON:

{
    "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"]
        }
    ]
}

我能够解析“question”和“correct_answer”,但我不确定如何解析错误的答案。

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;

}

}

我如何解析“问题”和“correct_answer”:

 myArray = myObj.getJSONArray("results");
 JSONObject tempObj = myArray.getJSONObject(0);
 question = tempObj.getString("question");
 A = tempObj.getString("correct_answer");

0 个答案:

没有答案