'Multiple JSONs in one Request --> Each of them to an Object
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
}
]
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JCompetence |
