使用JSON时,HashMap toJson为空

时间:2016-02-15 06:16:28

标签: java moshi

以下输出:

private static class Target extends HashMap<String, String> {
}

public static void main(String[] args) {
    final Moshi build = new Moshi.Builder().build();
    final JsonAdapter<Target> adapter = build.adapter(Target.class);
    final Target value = new Target();
    value.put("foo", "bar");
    System.out.println(adapter.toJson(value));
}

{} - 我希望{"foo":"bar"} - 如何获得预期的输出?

1 个答案:

答案 0 :(得分:3)

创建JsonAdapter时使用Map类而不是Target

private static class Target extends HashMap<String, String> {
}

public static void main(String[] args) {
    final Moshi build = new Moshi.Builder().build();
    final JsonAdapter<Map> adapter = build.adapter(Map.class);
    final Target value = new Target();
    value.put("foo", "bar");
    System.out.println(adapter.toJson(value));
}