使用Gson

时间:2016-02-11 20:41:51

标签: java gson linkedhashmap

我试图将JSON反序列化为一个用Gson扩展LinkedHashMap的类。我能够直接将这一点直接写入LinkedHashMap,但是当我尝试使用LinkedHashMap的子类时,我收到了错误

  

java.lang.IllegalStateException:预期为BEGIN_OBJECT但在第1行第3行路径为STRING。

我需要使用的类型(我不拥有此类,因此无法使用其他任何选项):

public class ValueMap extends LinkedHashMap<CharSequence, Object> {}

我必须定义一个InstanceCreator来解决CharSequence的问题。我试图反序列化的JSON是一个基本的例子:

{"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"]}]}

更新以包含序列化/反序列化代码:

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

CharSequenceInstanceCreator的样子:

public static class CharSequenceInstanceCreator implements InstanceCreator<CharSequence> {

    @Override
    public CharSequence createInstance(Type arg0) {
        return new String();
    }

}

1 个答案:

答案 0 :(得分:1)

定义JsonDeserializer而不是InstanceCreator。

public static class CharSequenceDeserializer implements JsonDeserializer<CharSequence> {

    @Override
    public CharSequence deserialize(JsonElement element, Type type,
            JsonDeserializationContext context) throws JsonParseException {
        return element.getAsString();
    }

}

并注册。

//  gsonBuilder.registerTypeAdapter(CharSequence.class, new CharSequenceInstanceCreator());
gsonBuilder.registerTypeAdapter(CharSequence.class, new CharSequenceDeserializer());