gpt4 book ai didi

java - 在 Android Studio 的 Java 中解析 JSON 的问题

转载 作者:行者123 更新时间:2023-11-29 08:26:49 25 4
gpt4 key购买 nike

我正在学习基本的 Java 应用程序创建,并且认为到目前为止我做得还不错,但是我在解析来自服务器的 JSON 响应方面遇到了问题。

我什至不确定我的回复是否正确构建。

响应表单服务器:

[{"Q_Number":"1","Question":"This is Q1"},{"Q_Number":"2","Question":"This is Q2"},{"Q_Number":"3","Question":"This is Q3"}]

如您所见,服务器给出了三个问题,标记为 1 - 3。理想情况下,我想要的是将 JSON 解析为标记为以下的字符串:q1String q2String q3String

我在这里尝试了多种解析代码形式,并试图让它对我有用。这是我目前凌乱的代码:

String jsonString = a.toString();
try {
JSONObject json = new JSONObject(jsonString);

JSONObject jsonOb = json.getJSONObject("1");

String str_value=jsonOb.getString("Question");

Log.i("JSON",str_value);

} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}

这是我得到的最后一个错误:

org.json.JSONException: Value [{"Q_Number":"1","Question":"This is Q1"},{"Q_Number":"2","Question":"This is Q2"},{"Q_Number":"3","Question":"This is Q3"}] of type org.json.JSONArray cannot be converted to JSONObject

最佳答案

您应该将源字符串转换为 JSONArray 而不是 JSONObject
请试试这个

    String jsonString = a.toString();
try
{
JSONArray json = new JSONArray(jsonString);
for(int index = 0; index < json.length(); ++index)
{
JSONObject obj = json.getJSONObject(index);
String str_value = obj.getString("Question");
Log.i("JSON", str_value);
}
}
catch (JSONException e)
{
e.printStackTrace();
// Do something to recover ... or kill the app.
}

关于java - 在 Android Studio 的 Java 中解析 JSON 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com