【发布时间】:2019-04-23 16:34:26
【问题描述】:
我得到了这个无名的 json 数组
[ { "symbol": "AAPL", "price": 207.1, "updated_at": "2019-04-23 16:26:09" }, { "symbol": "FB", "price": 183.12, "updated_at": "2019-04-23 16:26:09" } ]
但我的代码使用命名数组,如下所示:
{
"stocks": [
{
"symbol": "AAPL",
"price": 205.98,
"updated_at": "2019-04-23 15:18:25"
},
{
"symbol": "FB",
"price": 182.99,
"updated_at": "2019-04-23 15:18:25"
}
]
}
我不知道如何解析无名数组。它只有在命名时才有效,像这样(我将json数据数组命名为stocks)。
try {
JSONArray jsonArray = response.getJSONArray("stocks");
如何使它与无名数组一起使用? 我想使用第一个注释掉的 url。
private void jsonParse() {
// String url = "https://financialmodelingprep.com/api/company/real-time-price/AAPL,FB,GOOG,RHT,NOK,INTC?datatype=json";
String url = "https://api.myjson.com/bins/134wfc";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//I call the array stocks, but it doesn't have a name from the server, so it wont show.
try {
JSONArray jsonArray = response.getJSONArray("stocks");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stock = jsonArray.getJSONObject(i);
String symBol = stock.getString("symbol");
int value = stock.getInt("price");
mTextViewResult.append(symBol + ", " + String.valueOf(value) + " $\n" );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
【问题讨论】:
-
只是猜测...由于响应是 JSONArray,我的猜测是
new Response.Listener<JSONObject>和public void onResponse(JSONObject response) {应该将JSONObject替换为JSONArray。此外,JsonObjectRequest request = new JsonObjectRequest可能需要更改为请求数组的内容。检查是否有JsonArrayRequest。