【问题标题】:Nested Array Parsing for converting to a Json through Moshi用于通过 Moshi 转换为 Json 的嵌套数组解析
【发布时间】:2018-03-28 21:14:49
【问题描述】:

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

【问题讨论】:

    标签: arrays json parsing moshi


    【解决方案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);
      }
    }
    

    【讨论】:

    • 非常感谢@Eric Cochran。实际上我自己也做过类似的事情。忘记在此处更新评论:)。
    • 类结构 { 字符串用户;字符串密码;字符串存储;列出 类别;私有结构() { this.user = "sam"; this.password = "abcd1234"; this.store = "豆芽"; this.categories = new Categories("banana") } private Class Categories{ String fruitName;私人类别(字符串水果){水果名称=水果;}}
    猜你喜欢
    • 2018-12-25
    • 2018-04-09
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多