用 Moshi 解析多态 child

Parse polymorphic child with Moshi

我在这里问是因为我认为这与 Moshi GitHub 问题无关。

我有卡片 json 变体 #1:

{ "id":"some id",
  "type":"GENERIC_MESSAGE",
  "data": { "title":"Small error",
            "message":"Please update some info",
            "type":"ERROR"
          }
}

和变体#2:

{ "id":"some id",
  "type":"DATA_SCIENCE",
  "data": { "cardData": 
             { "message":"You spent...",
               "title":"...last month"}
             }    
          }
}

这是我的通用 JSON 适配器代码:

public class CardJsonAdapter
{
  @Keep
  static class CardJson
  {
    String id;
    Card.Type type;
    JSONObject data; <--- HERE is my problem
  }

  @FromJson
  Card fromJson(@NonNull final CardJson json)
    throws IOException
  {
    try
    {
      CardData data = getCardData(json);
      return new Card(json.id, json.type, data);
    }
    catch (JSONException e)
    {
      throw new JsonDataException("Can not parse Card json");
    }
  }

  private CardData getCardData(final @NonNull CardJson json)
    throws JSONException
  {
    CardData data = null;

    switch (json.type) 
    ...
  }
...
}

所以通过卡type,我已经知道如何解析data object。但我不知道如何获得数据中的通用内容。我无法将类型设置为 String,因为 MoshiBEGIN_OBJECT not expected error 而崩溃,我无法将 Map<String, Object> 设置为它也因第二个错误而失败json。并且 JsonObject 不会因解析而崩溃,而是在解析后完全为空。

我还没有找到任何东西,所以我正在征求你的意见

我找到了解决方案:

public class CardJsonAdapter
{
  @Keep
  static class CardDataJson 
  {
    String title;
    String message;
    String type;
    CardDataJson cardData;
  }

  @Keep
  static class CardJson
  {
    String id;
    Card.Type type;
    CardDataJson data;
  }

  @FromJson
  Card fromJson(@NonNull final CardJson json)
    throws IOException
  {
    try
    {
      CardData data = getCardData(json);
      return new Card(json.id, json.type, data);
    }
    catch (JSONException e)
    {
      throw new JsonDataException("Can not parse Card json");
    }
  }

  private CardData getCardData(final @NonNull CardJson json)
    throws JSONException
  {
    CardData data = null;

    switch (json.type) 
    ...
  }
...
}

Moshi 只是清空 json

中不存在的字段