用Moshi解析多态性的孩子

时间:2016-06-06 13:56:31

标签: json 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对象。但我不知道如何在数据中获得通用的东西。我无法将类型设置为String,因为 Moshi BEGIN_OBJECT not expected error崩溃,我无法将其Map<String, Object>与第二个的错误同时失败JSON 即可。并且JsonObject在解析时没有崩溃,但在解析后完全为空。

我找不到任何东西,所以我问你的建议

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

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中不存在的字段归零