I'm trying to deserialize from JSON into a class that extends LinkedHashMap with Gson. I'm able to do this trivially directly into a LinkedHashMap, but when I try to use the sub-class of LinkedHashMap, I get the error
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $.
The type I need to use (I don't own this, so there's no option to use anything else):
public class ValueMap extends LinkedHashMap<CharSequence, Object> {}
I've had to define an InstanceCreator to work around issues with CharSequence. The JSON I'm trying to deserialize as a basic example is:
{"people":[{"name":"name1","surname":"name2","age":12,"dogs":["spot","fluffy","batman"],"cars":[{"name":"name1","model":1933},{"name":"name2","model":343}]},{"name":"name2","surname":"name2","age":44,"dogs":["spot","test","jack"]}]}
Updated to include serialization/deserialization code:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(CharSequence.class, new CharSequenceInstanceCreator());
Gson gson = gsonBuilder.create();
String serialized = gson.toJson(value);
LinkedHashMap<CharSequence, Object> deserialized = gson.fromJson(serialized, ValueMap.class);
Where CharSequenceInstanceCreator looks like:
public static class CharSequenceInstanceCreator implements InstanceCreator<CharSequence> {
@Override
public CharSequence createInstance(Type arg0) {
return new String();
}
}
Define JsonDeserializer instead of InstanceCreator.
public static class CharSequenceDeserializer implements JsonDeserializer<CharSequence> {
@Override
public CharSequence deserialize(JsonElement element, Type type,
JsonDeserializationContext context) throws JsonParseException {
return element.getAsString();
}
}
and register it.
// gsonBuilder.registerTypeAdapter(CharSequence.class, new CharSequenceInstanceCreator());
gsonBuilder.registerTypeAdapter(CharSequence.class, new CharSequenceDeserializer());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.