嵌套数组解析用于通过Moshi转换为Json

时间:2018-03-28 21:14:50

标签: arrays json parsing moshi

我有一个这种格式的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中的类别传递给它。如何使用具有相同代码的类别?另外,我的班级结构需要进行哪些修改?

1 个答案:

答案 0 :(得分: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);
  }
}