[英]Java ClassCastException on getting JSON parsed java object
嗨,我在Java中遇到了問題。 問題是按照我的指示,用Jackson解析JSON。 我的JSON解析得很好,這不是問題。 問題在於我在一個JSON中有多個JSON項目。 我已經這樣解析:
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Unit> unitList = objectMapper.readValue(json,List.class);
System.out.println("UnitSize " + String.valueOf(unitList.size()));
System.out.println(unitList.get(0).getUnitEmail());
} catch (IOException e) {
e.printStackTrace();
}
並以UnitSize告訴我,我恰好有5個Unit類型的對象,這是可以的,但是當我想從List中獲取某些內容時,它會告訴我:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.reddatura.API.HTTPRequest$Unit
我已經用谷歌搜索了,但是沒有任何關系。 應該是什么問題
編輯:
這是我的課堂摘要:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Unit
{
@JsonProperty("unitid")
int unitId;
@JsonProperty("unitname")
String unitName;
@JsonProperty("unitlogo")
String unitLogo;
@JsonProperty("unitaddress")
String unitAddr;
//other fields, getters setters
@JsonCreator
public Unit()
{
}
}
我想解析成這個模型
我認為您沒有正確轉換json值:
使用jackson
您可以執行以下操作:
List<Unit> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
constructCollectionType(List.class, Unit.class));
希望能幫助到你 :)
嘗試這個
ObjectMapper objectMapper = new ObjectMapper();
try {
Unit[] unit = objectMapper.readValue(jsonString, Unit[].class);
Log.i("TEST", String.valueOf(unit.length)+" ******* "+unit[1].getUnitEmail()+" ******* "+unit[1].getUnitName());
// or
List<Unit> unit1 = objectMapper.readValue(jsonString, new TypeReference<List<Unit>>() { });
Log.i("TEST_1", String.valueOf(unit1.size())+" ****11111*** "+unit1.get(1).getUnitEmail()+" **1111111**** "+unit1.get(1).getUnitName());
} catch (IOException e) {
e.printStackTrace();
}
做這樣的事情:
JSONObject jObject = new JSONObject(jsonString);
JSONArray jsonArray = jObject.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
int a = jsonArray.getJSONObject(i).getInt("a"),
String s = jsonArray.getJSONObject(i).getString("b"));
}
jsonString是String變量,必須是Json語法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.