[英]How to parse this JSON into java object?
大家好,我一直在嘗試將上述JSON解析為Java程序並將其存儲到對象中……(目前我沒有特定的結構,只要我可以從對象中獲取數據即可。)
一直在嘗試使用GSON,但我似乎無法正確使用它。
String inputLine="";
HttpClient httpclient= new DefaultHttpClient();
HttpGet method = new HttpGet("http://localhost:3000/specs/215/errors.js");
HttpResponse response =httpclient.execute(method);
BufferedReader in = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(inputLine).getAsJsonArray();
for(int i=0; i < array.size(); i++) {
Errors e = gson.fromJson(array.get(0), Errors.class);
System.out.println(e.error.getReason());
}
我得到的錯誤是:
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:99)
at test.Getter.main(Getter.java:37)
有人請指出正確的方向嗎? 謝謝。
JSON字符串不是JSON數組字符串。 JSON字符串分別以{
, }
開頭和結尾,而JSON Array分別以[
, ]
開頭和結尾。
這行是錯誤的:
JsonArray array = parser.parse(inputLine).getAsJsonArray();
而是將其檢索為JsonObject
。
我解決了我遇到的問題。 新手錯誤的序列化注釋。 由於某種原因,我認為他們會引用類的名稱而不是字段名稱。 但更重要的是,我還必須創建一個根級容器類來保存我的類。 這樣就可以解析所有對象。
JSON結構可實現為對象,記錄,結構,字典,哈希表,鍵列表或關聯數組。
您可以使用eval()函數實現所需的目標。 我認為這會幫助您/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.