com.google.gson.internal.LinkedHashTreeMap无法强制转换为我的对象

我有JSON文件的样子

{ "SUBS_UID" : { "featureSetName" : "SIEMENSGSMTELEPHONY MULTISIM", "featureName" : "MULTISIMIMSI", "featureKey" : [{ "key" : "SCKEY", "valueType" : 0, "value" : "0" } ] }, } 

所以键是一个字符串“SUBS_ID”,该值是一个名为FeatureDetails的模型,它包含属性“featureSetName,featureName,…”。 所以我像这样使用google.json lib从JSON文件中读取,

 HashMap 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; private String groupKey; private String groupValue; public FeatureDetails() { featureKey = new ArrayList(); } public ArrayList getFeatureKey() { return featureKey; } public void setFeatureKey(ArrayList 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”。

尝试这个:

 HashMap featuresFromJson = new Gson().fromJson(JSONFeatureSet, new TypeToken>() {}.getType()); 

当你浏览你的哈希映射时,执行以下操作:

 for (Map.Entry entry : featuresFromJson.entrySet()) { FeatureDetails featureDetails = entry.getValue(); } 

您之所以看到这个原因,是因为您告诉GSON使用行中HashMap的结构反序列化JSON结构

 ... = new Gson().fromJson(JSONFeatureSet, HashMap.class); ^^ Right here 

因此,即使结构可能与FeatureDetails对象的结构匹配,GSON也不知道JSON中的子对象是除简单键值对之外的任何东西。

一种解决方案是创建一个包装FeatureDetails对象的模型,该对象将充当整个结构的根。 此对象可能如下所示:

 public class FeatureDetailsRoot{ private FeatureDetails SUBS_UID; // poor naming, but must match the key in your JSON } 

最后,你将通过该模型的课程:

 = new Gson().fromJson(JSONFeatureSet, FeatureDetailsRoot.class) 

更新

在关于添加/拥有多个FeatureDetails对象的能力的评论中回答您的问题,目前的问题是您的JSON没有反映这种结构。 意思是, "SUBS_UID"键指向单个对象,而不是数组对象。 如果你想拥有这个能力,那么你的json需要被改变,以便它显示一个对象数组,如下所示:

 { "SUBS_UID" : [{ "featureSetName" : "Feature set name #1", ...attributes for feature #1 }, { "featureSetName" : "Feature set name #2", ...attributes for feature #2 }, ...other features ] } 

然后你可以简单地改变根类,使它包含一个FeatureDetails对象列表,如下所示:

 public class FeatureDetailsRoot{ private List SUBS_UID; } 

让我知道这是否有意义(或者我是否误解了你)

代码在Kotlin中:使用val type = object : TypeToken>() {}.type Gson().fromJson(dataStr, type)

而不是val type = object : TypeToken>() {}.type Gson().fromJson(dataStr, type)注意:HashMap而不是Map