SinSri
SinSri

Reputation: 11

Nested Array Parsing for converting to a Json through Moshi

I have a JSON string of this format

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

I was thinking I create a class of Structure like this

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

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

And to parse the JSON, I can simply do it through Moshi through the following lines of code:

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

But, I also want to pass categories from my given JSON into this. How do I use categories with the same code? Also, what modifications are needed from my class structure?

Upvotes: 1

Views: 1083

Answers (1)

Eric Cochran
Eric Cochran

Reputation: 8574

Use a Java class to represent the category JSON object, just like you did for the Structure JSON object.

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);
  }
}

Upvotes: 1

Related Questions