我正在尝试用Java解析JSON响应,但由于响应是数组格式而不是对象,因此面临困难。我首先引用了这个link但是找不到正确解析JSON的解决方案。相反,我在尝试显示已解析的数据时收到此错误...
Exception in thread "main" org.json.JSONException: JSONObject["cardBackId"] not found.
用于显示数据的代码段:
JSONObject obj = new JSONObject(response);
JSONArray cardBackId = (JSONArray) obj.get("cardBackId");
System.out.println(cardBackId);
邮递员的数据回复:
[
{
"cardBackId": "0",
"name": "Classic",
"description": "The only card back you'll ever need.",
"source": "startup",
"sourceDescription": "Default",
"enabled": true,
"img": "http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png",
"imgAnimated": "http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif",
"sortCategory": "1",
"sortOrder": "1",
"locale": "enUS"
},
虽然没有JSONObject我在Java中提取数据并通过在STDOUT中使用response.toString进行验证,这是我第一次在Java中使用json库,重要的是我将这些数据解析为json。任何有关此建议都是有帮助的。
答案 0 :(得分:1)
响应是一个数组,而不是对象本身,试试这个:
JSONObject obj = new JSONArray(response).getJSONObject(0);
String cardBackId = obj.getString("cardBackId");
以下是输出以及相关的files used:
答案 1 :(得分:0)
答案 2 :(得分:0)
使用Gson library查看此示例,您需要在其中定义数据类型以定义如何解析JSON。
示例的关键部分是:Data [] data = gson.fromJson(json,Data [] .class);
package foo.bar;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Main {
private class Data {
long cardBackId;
String name;
}
public static void main(String[] args) throws FileNotFoundException {
// reading the data from a file
BufferedReader reader = new BufferedReader(new FileReader("data.json"));
StringBuffer buffer = new StringBuffer();
reader.lines().forEach(line -> buffer.append(line));
String json = buffer.toString();
// parse the json array
Gson gson = new Gson();
Data[] data = gson.fromJson(json, Data[].class);
for (Data item : data) {
System.out.println("data=" + item.name);
}
}
}