大家好,我在 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
我用谷歌搜索过,但没有任何相关内容。应该是什么问题
编辑:
这是我的类(class) fragment :
@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));
希望有帮助:)
关于获取 JSON 解析的 java 对象时出现 Java ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502867/