gson在自定义反序列化器中调用标准反序列化

时间:2010-10-14 11:36:39

标签: java json gson

是否可以在gson中编写一个json反序列化器,首先调用默认行为然后我可以对我的对象进行一些后期处理。例如:

public class FooDeserializer implements JsonDeserializer<Foo> {
    public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {      
        Foo foo = context.deserialize(json, typeOfT);//Standard deserialization call?????
        foo.doSomething();
        return foo();
    }
}   

我正在使用gson 1.3(我不能使用任何其他版本,因为我只能使用公司版本 库)

感谢

5 个答案:

答案 0 :(得分:3)

您可以通过为您的对象(比如CustomClass.class)实现自定义TypeAdapterFactory来进行反序列化,如下所示。

 public class CustomTypeAdapterFactory implements TypeAdapterFactory {

    public final TypeAdapter create(Gson gson, TypeToken type) {
     return new TypeAdapter() {
            @Override 
            public void write(JsonWriter out, Object value) throws IOException {
                JsonElement tree = delegate.toJsonTree(value);
                //add code for writing object
            }

            @Override 
            public Object read(JsonReader in) throws IOException {
                JsonElement tree = elementAdapter.read(in);
                //Add code for reading object
            }
        };
    }
  }

然后将其注册为Gson

Gson gson = new GsonBuilder().registerTypeAdapter(CustomClass.class,new CustomTypeAdapterFactory()).create();

答案 1 :(得分:2)

public class FooDeserializer implements JsonDeserializer<Foo> {
public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {      
    Foo foo=new Gson().fromJson(json, Foo.class); // use default Gson object
    foo.doSomething();
    return foo;
}

答案 2 :(得分:0)

public class YourDeserializer<Foo> extends FooDeserializer<Foo>  
 {  
     public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)    throws JsonParseException {       
        Foo foo = super.deserialize(json, typeOfT,context);  
        foo.doSomething();  //put logic   
        return foo();  
    }  
}  

答案 3 :(得分:0)

查看http://gsonfire.io

这是我创建的一个库,它扩展了Gson来处理序列化后和反序列化后的案例

与Gson一起,它还有许多其他很酷的功能。

答案 4 :(得分:0)

以下是基于@ user1556622提供的不完整答案以及code.google.com/p/google-gson/issues/detail?id=43中讨论的完整实施。

因此,我们可以序列化抽象Field对象列表,并根据特定Field及其层次深度的具体实现,对其进行平滑反序列化。

class MyClass { //class which we would like to serialiaze/deserialize
   List<Field> fields; //field is an hierarchy of classes
}


/**
 * Purpose of this adapter is simple:
 * 1) put during serialization in all Field objects additional property describing class
 * 2) during deserialization invoke (based on class info) necessary deserializer to create class
 */

public class FieldTypeAdapterFactory implements TypeAdapterFactory {
    private static final String CLASS_META_KEY="clz";
    Gson gson;
    TypeToken<?> type;
    TypeAdapter<Field> fieldAdapter;
    TypeAdapter<JsonElement> elementAdapter;
    TypeAdapterFactory taf;

    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        if (!Field.class.isAssignableFrom(type.getRawType()))
            return null; // this class only serializes 'Field' and its subtypes

        this.type=type;
        this.gson=gson;
        this.taf=this;
        fieldAdapter = gson.getDelegateAdapter(taf, TypeToken.get(Field.class));
        elementAdapter = gson.getAdapter(JsonElement.class);
        TypeAdapter<T> result = new FieldTypeAdapter<T>();
        result.nullSafe();
        return result;
    }

    class FieldTypeAdapter<T> extends TypeAdapter<T> {

        public FieldTypeAdapter() {
        }

        @Override
        public void write(JsonWriter out, Object value) throws IOException {
            if(value instanceof Field) {
                JsonObject object = fieldAdapter.toJsonTree((Field )value).getAsJsonObject();
                object.addProperty(CLASS_META_KEY, value.getClass().getCanonicalName());
                elementAdapter.write(out, object);
            }
            else {
                elementAdapter.write(out, (JsonElement) value);
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonObject object = elementAdapter.read(in).getAsJsonObject();
            if (object.has(CLASS_META_KEY)) {
                String className=object.get(CLASS_META_KEY).getAsString();
                try {
                    Class<?> clz = Class.forName(className);
                    TypeAdapter<?> adapter = gson.getDelegateAdapter(taf, TypeToken.get(clz));
                    return (T) adapter.fromJsonTree(object);
                }
                catch (Exception e) {
                    return (T )fieldAdapter.fromJsonTree(object);
                }
            }
            else
                return (T )elementAdapter.fromJsonTree(object);
        }
    }
}

工厂注册:

Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(new FieldTypeAdapterFactory())
                .create();