0

I am requesting via OKHttpClient data from my api, and im trying with an getAll() to split up the JSON response into my objects i need. Here is an example for my response i get:

[
  {
     "value":"data",
     "id":5
  },
  {
     "value":"data",
     "id":6
  },
  {
     "value":"data",
     "id":7
  },
  {
     "value":"data",
     "id":8
  },
  {
     "value":"data",
     "id":9
  },
  {
     "value":"value",
     "id":10
  }
]

1 Answers1

0

I believe you can use GSON in Android, so kindly see the code below:

static class SimpleExample{

    private String value;
    private Integer id;

}
public static void main(String[] args){


    String json = "[{\n"
            + "     \"value\":\"data\",\n"
            + "     \"id\":5\n"
            + "  },\n"
            + "  {\n"
            + "     \"value\":\"data\",\n"
            + "     \"id\":6\n"
            + "  },\n"
            + "  {\n"
            + "     \"value\":\"data\",\n"
            + "     \"id\":7\n"
            + "  },\n"
            + "  {\n"
            + "     \"value\":\"data\",\n"
            + "     \"id\":8\n"
            + "  },\n"
            + "  {\n"
            + "     \"value\":\"data\",\n"
            + "     \"id\":9\n"
            + "  },\n"
            + "  {\n"
            + "     \"value\":\"value\",\n"
            + "     \"id\":10\n"
            + "  }\n"
            + "]";

    final GsonBuilder gsonBuilder = new GsonBuilder();
    final Gson gson = gsonBuilder.create();

    SimpleExample[] allObjects = gson.fromJson(json, SimpleExample[].class);

    System.out.println(allObjects.length);
}

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

JCompetence
  • 6,997
  • 3
  • 19
  • 26