我读了一些关于"ClassCastException"的文章,但我无法对此有所了解.是否有一篇好文章或什么是简短的解释?
我有一个应用程序,它使用Jackson将一些数据存储在DynamoDB中,以便将我的复杂对象编组为JSON.
例如,我正在编组的对象可能如下所示:
private String aString;
private List<SomeObject> someObjectList;
Run Code Online (Sandbox Code Playgroud)
SomeObject可能如下所示:
private int anInteger;
private SomeOtherObject;
Run Code Online (Sandbox Code Playgroud)
和SomeOtherObject可能如下所示:
private long aLong;
private float aFloat;
Run Code Online (Sandbox Code Playgroud)
这很好,对象被编组没有问题,并作为JSON字符串存储在DB中.
当需要从DynamoDB检索数据时,Jackson会自动检索JSON并将其转换回来...除了'someObjectList'返回的List<LinkedHashMap>不是List<SomeObject>!这是杰克逊的标准行为,这不是一个错误.
所以现在这会导致问题.我的代码库认为它处理一个List<SomeObject>但现实是它处理一个List<LinkedHashMap>!我的问题是如何让我的LinkedHashMap回到'SomeObject'.显然这是一个手动过程,但我的意思是我甚至无法提取值.
如果我这样做:
for (LinkedHashMap lhm : someObjectList) {
// Convert the values back
}
Run Code Online (Sandbox Code Playgroud)
我收到一个编译错误,告诉我someObjectList的类型为'SomeObject'而不是LinkedHashMap.
如果我这样做:
for (SomeObject lhm : someObjectList) {
// Convert the values back
}
Run Code Online (Sandbox Code Playgroud)
我收到运行时错误,告诉我LinkedHashMap无法转换为'SomeObject'.
我有JSON文件的样子
{
"SUBS_UID" : {
"featureSetName" : "SIEMENSGSMTELEPHONY MULTISIM",
"featureName" : "MULTISIMIMSI",
"featureKey" : [{
"key" : "SCKEY",
"valueType" : 0,
"value" : "0"
}
]
},
}
Run Code Online (Sandbox Code Playgroud)
所以键是一个字符串"SUBS_ID",该值是一个名为FeatureDetails的模型,它包含属性"featureSetName,featureName,...".所以我像这样使用google.json lib从JSON文件中读取,
HashMap<String, FeatureDetails> featuresFromJson = new Gson().fromJson(JSONFeatureSet, HashMap.class);
Run Code Online (Sandbox Code Playgroud)
然后我试图循环这个HashMap获取值并将其转换为我的FeatureDetails模型,
for (Map.Entry entry : featuresFromJson.entrySet()) {
featureDetails = (FeatureDetails) entry.getValue();
}
Run Code Online (Sandbox Code Playgroud)
这是我的FeatureDetails模型,
public class FeatureDetails {
private String featureSetName;
private String featureName;
private ArrayList<FeatureKey> featureKey;
private String groupKey;
private String groupValue;
public FeatureDetails() {
featureKey = new ArrayList<FeatureKey>();
}
public ArrayList<FeatureKey> getFeatureKey() …Run Code Online (Sandbox Code Playgroud)