1

我有一个这种格式的 JSON 字符串

{
  "user": "sam",
  "password": "abcd1234",
  "categories":
    [
      {
        "fruit name": "watermelon"
      },
      {
        "fruit name":"jackfruit"
      },
      {
        "fruit name": "kiwi"
      }
    ],
  "store":"SPROUTS"
}

我在想我创建一个这样的结构类

class Structure {
  String user;
  String password;
  String store;

  private Structure() {
    this.user = "sam";
    this.password = "abcd1234";
    this.store = "SPROUTS";
  }
}

为了解析 JSON,我可以通过 Moshi 简单地通过以下代码行来完成:

Moshi moshi = new Moshi.Builder().build();
Structure structure = new Structure();
String json = moshi.adapter(Structure.class).indent(" ").toJson(structure);

但是,我还想将给定 JSON 中的类别传递给它。如何使用具有相同代码的类别?另外,我的班级结构需要进行哪些修改?

4

1 回答 1

1

使用 Java 类来表示类别 JSON 对象,就像您对 Structure JSON 对象所做的那样。

public final class Structure {
  public final String user;
  public final String password;
  public final String store;
  public final List<Category> categories;

  Structure(String user, String password, String store, List<Category> categories) {
    this.user = user;
    this.password = password;
    this.store = store;
    this.categories = categories;
  }

  public static final class Category {
    @Json(name = "fruit name") public final String fruitName;

    Category(String fruitName) {
      this.fruitName = fruitName;
    }
  }

  public static void main(String[] args) throws Exception {
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<Structure> adapter = moshi.adapter(Structure.class);
    String json = "{\n"
        + "  \"user\": \"sam\",\n"
        + "  \"password\": \"abcd1234\",\n"
        + "  \"categories\":\n"
        + "    [\n"
        + "      {\n"
        + "        \"fruit name\": \"watermelon\"\n"
        + "      },\n"
        + "      {\n"
        + "        \"fruit name\":\"jackfruit\"\n"
        + "      },\n"
        + "      {\n"
        + "        \"fruit name\": \"kiwi\"\n"
        + "      }\n"
        + "    ],\n"
        + "  \"store\":\"SPROUTS\"\n"
        + "}";
    Structure value = adapter.fromJson(json);
  }
}
于 2018-03-30T22:43:22.920 回答