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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19796590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:16:28  来源:igfitidea点击:

com.google.gson.internal.LinkedHashTreeMap cannot be cast to my object

javajsongson

提问by Islam

I have JSON file looks like

我有 JSON 文件看起来像

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

So the key is a String "SUBS_ID" and the value is a model called FeatureDetails which contains attributes "featureSetName,featureName,...". So i read from the JSON file using google.json lib like this,

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

HashMap<String, FeatureDetails> featuresFromJson = new Gson().fromJson(JSONFeatureSet, HashMap.class);

then I'm trying to loop over this HashMap getting the value and cast it to my FeatureDetails model,

然后我试图遍历这个 HashMap 获取值并将其转换为我的 FeatureDetails 模型,

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

and here is my FeatureDetails Model,

这是我的 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;
    }
} 

but i got an exception "com.google.gson.internal.LinkedHashTreeMap cannot be cast to com.asset.vsv.models.FeatureDetail".

但我遇到了一个异常“com.google.gson.internal.LinkedHashTreeMap 无法转换为 com.asset.vsv.models.FeatureDetail”。

采纳答案by Алексей

try this:

尝试这个:

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

and when you going through your hash map do this:

当您浏览哈希图时,请执行以下操作:

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

回答by Paul Richter

The reason you're seeing this is because you're telling GSON to deserialize the JSON structure using the structure of a HashMapin the line

您看到这一点的原因是因为您告诉 GSON 使用HashMap行中 a 的结构反序列化 JSON 结构

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

As a result, GSON has no idea that the sub objects in the JSON are anything other than simple key-value pairs, even though the structure may match the structure of your FeatureDetailsobject.

因此,GSON 不知道 JSON 中的子对象不是简单的键值对,即使结构可能与您的FeatureDetails对象的结构相匹配。

One solution is to create a model which wraps your FeatureDetailsobject, which will act as the root of the entire structure. This object might look something like this:

一种解决方案是创建一个模型来包装您的FeatureDetails对象,它将充当整个结构的根。这个对象可能看起来像这样:

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

And finally, you'd pass that model's class:

最后,您将通过该模型的类:

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

Update

更新

In answer to your question in the comment regarding the ability to add / have multiple FeatureDetailsobjects, the problem presently is that your JSON does not reflect that kind of structure. Meaning, the "SUBS_UID"key points to a single object, not an array objects. If you would like to have this ability, then your json will need to be altered so that it shows an array of objects, like this:

在回答关于添加/拥有多个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
     ]
}

And then you can simply alter the root class so that it contains a list of FeatureDetailsobjects, like so:

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

public class FeatureDetailsRoot{
    private List<FeatureDetails> SUBS_UID;
}

Let me know if that makes sense (or whether I've misunderstood you)

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

回答by Abhilash Das

the code is in Kotlin: use val type = object : TypeToken<HashMap<String, FoodLogEntry>>() {}.type Gson().fromJson(dataStr, type)

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

instead of val type = object : TypeToken<Map<String, FoodLogEntry>>() {}.type Gson().fromJson(dataStr, type)note: HashMap instead of Map

代替val type = object : TypeToken<Map<String, FoodLogEntry>>() {}.type Gson().fromJson(dataStr, type)注释:HashMap 代替 Map