You can create a POJO class and then use libraries like Jackson or Gson to map the JSON string into an array of POJO instances. In this case I will use Jackson you can import it via maven with:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.0</version>
</dependency>
The POJO class. Note that I use the annotation @JsonProperty
to set the JSON field names so I can avoid using variable names that contain special characters.
import com.fasterxml.jackson.annotation.JsonProperty;
public class APIResponse {
@JsonProperty("$id")
private int id;
@JsonProperty("accommodation_type")
private String accommodationType;
@JsonProperty("max_people")
private int maxPeople;
public int getId() {
return id;
}
public int getMaxPeople() {
return maxPeople;
}
public String getAccommodationType() {
return accommodationType;
}
@Override
public String toString() {
return "APIResponse{" +
"id=" + id +
", accommodationType='" + accommodationType + '\'' +
", maxPeople=" + maxPeople +
'}';
}
}
Then you can deserialize using:
final String json = "[{\"$id\":\"1\",\"accommodation_type\":\"apartment\",\"max_people\":2},{\"$id\":\"2\",\"accommodation_type\":\"lodge\",\"max_people\":5}]";
final ObjectMapper mapper = new ObjectMapper();
APIResponse[] responses = mapper.readValue(json, APIResponse[].class);
for (APIResponse response: responses) {
System.out.println(response.toString());
}
Result:
APIResponse{id=1, accommodationType='apartment', maxPeople=2}
APIResponse{id=2, accommodationType='lodge', maxPeople=5}
Finally, you can access the data just by calling the getters in the POJO class:
responses[0].getId(); // 1
responses[1].getAccommodationType; // lodge
Then if you want the data separated by commas use:
public String[] getByComas(APIResponse[] responses) {
List<String> data = new ArrayList<>();
for (APIResponse response: responses) {
data.add("id,");
data.add(response.getId() + ",");
data.add("accommodation_type,");
data.add(response.getAccommodationType() + ",");
data.add("max_people,");
data.add(response.getMaxPeople() + ",");
}
return data.toArray(new String[data.size()]);
}
Then just use:
String[] formattedMessage = getByComas(responses);
for (String s: formattedMessage) {
System.out.print(s);
}
Result:
id,1,accommodation_type,apartment,max_people,2,id,2,accommodation_type,lodge,max_people,5,
Using JSON mappers is highly recommended as they are pretty reliable when parsing JSON data.
Let me know if this solves your problem!