gpt4 book ai didi

java - Android从字符串数组中获取volley数据

转载 作者:行者123 更新时间:2023-12-01 17:51:40 25 4
gpt4 key购买 nike

AM 使用 android volley 发送请求并得到如下响应

   public void onResponse(JSONObject response

try {
String responsedata = response.getString("data");

Log.i("test",responsedata);
} catch (JSONException e) {
e.printStackTrace();
}

}

上面的日志打印

[{"id":1,"identifier":"TYam Plant","header_val":"tyamplant"},
{"id":2,"identifier":"Touron Plant","header_val":"toroun"}
]

现在我想循环这些并提取一组单独的属性

id, identifier, header_val

我该如何解决这个问题。我对java还是新手

最佳答案

You response is JSONArray not JSONObject check it

您需要使用 JSONArray 请求,而不是 volleyJSONObject 请求

尝试解析你的 json

    try {
JSONArray jsonArray= new JSONArray(responsedata);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
}

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

最好使用 google-gson-library 解析您的 JSON

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of

示例:How to Parse JSON Array with Gson

关于java - Android从字符串数组中获取volley数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49442292/

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