我有一个JSON文件,看起来像
{
"SUBS_UID" : {
"featureSetName" : "SIEMENSGSMTELEPHONY MULTISIM",
"featureName" : "MULTISIMIMSI",
"featureKey" : [{
"key" : "SCKEY",
"valueType" : 0,
"value" : "0"
}
]
},
}因此,关键字是一个字符串"SUBS_ID“,值是一个名为FeatureDetails的模型,它包含属性"featureSetName,featureName,...”。所以我使用google.json库读取JSON文件,如下所示,
HashMap<String, FeatureDetails> featuresFromJson = new Gson().fromJson(JSONFeatureSet, HashMap.class);然后我尝试遍历这个获取值的HashMap并将其转换为我的FeatureDetails模型,
for (Map.Entry entry : featuresFromJson.entrySet()) {
featureDetails = (FeatureDetails) entry.getValue();
}这是我的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() {
return featureKey;
}
public void setFeatureKey(ArrayList<FeatureKey> featureKey) {
this.featureKey = featureKey;
}
public String getGroupKey() {
return groupKey;
}
public void setGroupKey(String groupKey) {
this.groupKey = groupKey;
}
public String getGroupValue() {
return groupValue;
}
public void setGroupValue(String groupValue) {
this.groupValue = groupValue;
}
public String getFeatureName() {
return featureName;
}
public void setFeatureName(String featureName) {
this.featureName = featureName;
}
public String getFeatureSetName() {
return featureSetName;
}
public void setFeatureSetName(String featureSetName) {
this.featureSetName = featureSetName;
}
} 但是我得到了一个异常"com.google.gson.internal.LinkedHashTreeMap不能被转换为com.asset.vsv.models.FeatureDetail“。
发布于 2013-11-06 03:06:28
试试这个:
HashMap<String, FeatureDetails> featuresFromJson = new Gson().fromJson(JSONFeatureSet, new TypeToken<Map<String, FeatureDetails>>() {}.getType());当您遍历您的哈希图时,请执行以下操作:
for (Map.Entry<String, FeatureDetails> entry : featuresFromJson.entrySet()) {
FeatureDetails featureDetails = entry.getValue();
}发布于 2018-06-14 18:07:43
代码在Kotlin中:使用val type = object : TypeToken<HashMap<String, FoodLogEntry>>() {}.type Gson().fromJson(dataStr, type)
代替val type = object : TypeToken<Map<String, FoodLogEntry>>() {}.type Gson().fromJson(dataStr, type)注意:用HashMap代替映射
发布于 2020-09-25 16:04:26
(objectName as Map<String, Any>).get("fieldName")https://stackoverflow.com/questions/19796590
复制相似问题