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

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

... = 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 FeatureDetails object.

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

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 FeatureDetails objects, 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:

{
    "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 FeatureDetails objects, like so:

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

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


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();
}

Tags:

Java

Json

Gson