如何阻止Moshi解析特定的对象属性

时间:2019-03-25 06:12:16

标签: android json retrofit moshi

(来自服务器的)我的JSON响应具有作为JSON对象的属性,但是我不想解析所有属性,而是希望将其中一些保留为JSON编码的字符串。

例如:

{
"date": "23-03-2019",
"changed": true,
"data": {
    "login": "9999999",
    "loginFormatted": "999 99 99",
    }
}

在这里,我想将“数据”属性解析为字符串。我该怎么做? (我正在使用Retrofit v2.4.0和Moshi v1.5.0)

我的响应模型类:

public class Response {
    @Json(name = "date")
    public long date;
    @Json(name = "changed")
    public boolean changed;
    @Json(name = "data")
    public String data;
}

1 个答案:

答案 0 :(得分:0)

当Moshi查看Response类的层次结构时,它决定使用JsonAdapter<String>来解析字段data。因此解决方案是告诉Moshi不要使用JsonAdapter<String>来解析它,而是将任务委托给我们的JsonAdapter

对话很便宜,这是代码。

class KeepAsJsonString {
  public void run() throws Exception {
    String json = "" +
      "{\n" +
      "\"date\": \"23-03-2019\",\n" +
      "\"changed\": true,\n" +
      "\"data\": {\n" +
      "    \"login\": \"9999999\",\n" +
      "    \"loginFormatted\": \"999 99 99\"\n" +
      "    }\n" +
      "}";

    Moshi moshi = new Moshi.Builder().add(new DataToStringAdapter()).build();
    JsonAdapter<Response> jsonAdapter = moshi.adapter(Response.class);

    Response response = jsonAdapter.fromJson(json);
    System.out.println(response.data); // {"login":"9999999","loginFormatted":"999 99 99"}
  }

  static class Response {
    @Json(name = "date")
    public String date;
    @Json(name = "changed")
    public boolean changed;
    // Ask moshi to forward the intermediate result to some function with a String annotated with @DataString,
    // in our case, DataToStringAdapter.fromJson() and DataToStringAdapter.toJson()
    @Json(name = "data")
    public @DataString String data;
  }

  @Retention(RUNTIME)
  @JsonQualifier
  public @interface DataString {
  }

  static class DataToStringAdapter {
    @ToJson
    void toJson(JsonWriter writer, @DataString String string) throws IOException {
      // Write raw JSON string
      writer.value(new Buffer().writeUtf8(string));
    }

    @FromJson @DataString
    String fromJson(JsonReader reader, JsonAdapter<Object> delegate) throws IOException {
      // Now the intermediate data object (a Map) comes here
      Object data = reader.readJsonValue();
      // Just delegate to JsonAdapter<Object>, so we got a JSON string of the object
      return delegate.toJson(data);
    }
  }

  public static void main(String[] args) throws Exception {
    new KeepAsJsonString().run();
  }
}

更新:

如埃里克·科克伦(Eric Cochran)所述,当固定此issue时,将有一种更有效的方式(JsonReader.readJsonString())以字符串形式读取JSON。