Retrofit,Gson和一系列异构对象

时间:2015-02-10 15:48:27

标签: android json gson deserialization retrofit

我正在使用Retrofit对我们的服务器执行REST请求。其中一个请求返回array个对象,这些对象在POJO中反序列化后,从abstract class Event延伸。事件的方法getEventType()返回String,此字符串是键"EventType"的值,我将始终在数组中的JSONObject内。

这就是JSON的样子(截至目前我们有7种类型的对象):

[
 {
  "EventType":"typeA",
  "Data":"data"
 }, 
 {
  "EventType":"typeB",
  "OtherData":3
 }
] 

我正在尝试使用RetrofitGSON API对异步调用中的JSON进行反序列化,以使用Callback<List<Event>>作为参数对于电话,但我仍然找不到办法。

3 个答案:

答案 0 :(得分:7)

您可以为此案例编写自定义Gson TypeAdapterFactory。问题是确定事件的类型,然后对该类型使用默认TypeAdapter。 这正是我所做的:

public class EventTypeAdapterFactory implements TypeAdapterFactory {
    private static final String TAG = EventTypeAdapterFactory.class.getSimpleName();

    private Map<EventType, TypeAdapter<? extends Event>> ADAPTERS = new ArrayMap<>();
    private TypeAdapter<Event> baseTypeAdapter;
    private TypeAdapter<JsonElement> elementAdapter;
    private TypeAdapter<EventType> eventTypeAdapter;

    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      if (!Event.class.isAssignableFrom(type.getRawType())) return null;

      ADAPTERS.put(EventType.TYPE_A, gson.getDelegateAdapter(this, TypeToken.get(TypeAEvent.class)));
      ADAPTERS.put(EventType.TYPE_B, gson.getDelegateAdapter(this, TypeToken.get(TypeBEvent.class)));

      baseTypeAdapter = gson.getDelegateAdapter(this, TypeToken.get(Event.class));

      elementAdapter = gson.getAdapter(JsonElement.class);
      eventTypeAdapter = gson.getAdapter(EventType.class);

      return (TypeAdapter<T>) new EventTypeAdapter().nullSafe();
    }

    private class EventTypeAdapter extends TypeAdapter<Event> {

      @Override public void write(JsonWriter out, Event value) throws IOException {
        EventType eventType = value.getType();
        TypeAdapter<? extends Event> adapter = eventType == null ? baseTypeAdapter : ADAPTERS.get(eventType);
        if (value instanceof TypeAEvent) {
          writeWrap(adapter, out, (TypeAEvent) value, TypeAEvent.class);
        } else if (value instanceof TypeBEvent) {
          writeWrap(adapter, out, (TypeBEvent) value, TypeBEvent.class);
        } else {
          writeWrap(adapter, out, value, Event.class);
        }
      }

      private <T extends Event> void writeWrap(TypeAdapter<? extends Event> adapter,
          JsonWriter out, T value, Class<T> dummyForT) throws IOException {
        ((TypeAdapter<T>)adapter).write(out, value);
      }

      @Override public Event read(JsonReader in) throws IOException {
        JsonObject objectJson = elementAdapter.read(in).getAsJsonObject();
        JsonElement typeJson = objectJson.get("EventType");

        EventType eventType = eventTypeAdapter.fromJsonTree(typeJson);

        if (eventType == null) {
          Log.w(TAG, "Unsupported EventType: " + typeJson);
        }

        TypeAdapter<? extends Event> adapter = eventType == null ? baseTypeAdapter : ADAPTERS.get(eventType);
        return adapter.fromJsonTree(objectJson);
      }
    }
  }

// EventType enum, change to reflect your values.
enum EventType {
    TYPE_A, TYPE_B; 
}

// Base Event type and its successors.
class Event {
    @SerializedName("EventType")
    private EventType type;

    public EventType getType() {
        return type;
    }
}

class TypeAEvent extends Event {
    @SerializedName("Data")
    public String data;
}

class TypeBEvent extends Event {
    @SerializedName("OtherData")
    public int otherData;
}

答案 1 :(得分:0)

我不确定,因为我没有对此进行测试,但是如果您编写这样的自定义反序列化器:

private class MyEventDeserialiser implements JsonDeserializer<Event> {

    @Override
    public Event deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {

        JsonArray jArray = (JsonArray) json;

        for (int i=1; i<jArray.size(); i++) {
            JsonObject obj = jArray.get(i).getAsJsonObject();
            String eventType = String.valueOf(obj.get("EventType"));

            //check here which type it is
            Event event = null;

            if(eventType.equals("TypeA")) {
                Event event = context.deserialize(obj, TypeA.class);    
            }
            ...

            return event;
        }
    }
}

然后在您用于Retrofit的Gson反序列化器上设置这个,它可能会有用。

您可能需要将事件列表封装在另一个类中,例如

public class EventResponse {
    List<Event> events;
}

然后在你的界面中使用它作为参数,但我不确定。

答案 2 :(得分:0)

与科里奥特的答案非常相似。我做了一些修改,以便将一个类嵌入到json中,并且只有在将其序列化时,该映射才有点难看。

它也没有那么健壮,因为我很高兴在null上失败。

public final class ModelTypeAdapter extends TypeAdapter<Model> {

    private static final String MODEL_CLASS_PROPERTY_NAME = "modelClass";

    private final Gson gson;
    private final TypeAdapterFactory containerFactory;

    @SuppressWarnings("rawtypes")
    private final TypeAdapter<Class> classTypeAdapter;
    private final TypeAdapter<JsonElement> jsonElementAdapter;

    public ModelTypeAdapter(final Gson gson, final TypeAdapterFactory containerFactory) {
        this.gson = gson;
        this.containerFactory = containerFactory;

        this.classTypeAdapter = gson.getAdapter(Class.class);
        this.jsonElementAdapter = gson.getAdapter(JsonElement.class);
    }

    @Override
    public final void write(JsonWriter out, Model value) throws IOException {
        doWrite(out, value);
    }

    private final <M extends Model> void doWrite(JsonWriter out, M value) throws IOException {
        @SuppressWarnings("unchecked")
        final Class<M> modelClass = (Class<M>) value.getClass();

        final TypeAdapter<M> delegateAdapter = gson.getDelegateAdapter(containerFactory, TypeToken.get(modelClass));
        final JsonObject jsonObject = delegateAdapter.toJsonTree(value).getAsJsonObject();
        jsonObject.add(MODEL_CLASS_PROPERTY_NAME, classTypeAdapter.toJsonTree(modelClass));

        jsonElementAdapter.write(out, jsonObject);
    }

    @Override
    public final Model read(JsonReader in) throws IOException {
        final JsonObject jsonObject = jsonElementAdapter.read(in).getAsJsonObject();
        @SuppressWarnings("unchecked")
        final Class<? extends Model> modelClass = classTypeAdapter.fromJsonTree(jsonObject.get(MODEL_CLASS_PROPERTY_NAME));

        jsonObject.remove(MODEL_CLASS_PROPERTY_NAME);
        final TypeAdapter<? extends Model> delegateAdapter = gson.getDelegateAdapter(containerFactory, TypeToken.get(modelClass));

        return delegateAdapter.fromJsonTree(jsonObject);
    }
}