'GET JSON response, parse it and then convert back to a JSON
My goal is;
- GET a JSON file from an API and make changes to the data
- Then generate a new dictionary from this data
- Convert this dictionary into JSON
So far I have points 1 and 2 complete but struggling to understand how I can convert the changes into a new JSON
Main.java
//get JSON from API
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://jsonplaceholder.typicode.com/albums")).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
//.thenAccept(System.out::println)
.thenApply(Main::parse)
.join();
}
//Parse Json
public static String parse(String responseBody) {
JSONArray albums = new JSONArray(responseBody);
for(int i = 0 ; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int userId = album.getInt("userId");
String title = album.getString("title");
System.out.println("id: " + id);
System.out.println("userId: " + userId);
System.out.println("title: " + title);
}
return null;
}
}
Thanks in advance
Solution 1:[1]
It depends on the library that contains JSONArray and JSONObject, but I've seen quite a few libraries where the toString() method returns the JSON you're looking for.
Solution 2:[2]
org.json is a simple library. It is possible to do what you want with this library but I can offer you much simpler solution. Your code may look something like this:
public static String parse(String responseBody) {
List<Map<String, Object>> myList = JsonUtils.readObjectFromJsonString(responseBody, List.class); //here you get a list of Maps that contasins your data
//Here you modify your data
return JsonUtils.writeObjectToJsonString(myList); //Here you convert your modified list of maps mack to Json String
}
You will need to get MgntUtils library to use JsonUtils class. You can get the library as maven artifact here or as just a jar file here. Here is Javadoc for JsonUtils class
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 | Rob Spoor |
| Solution 2 | Michael Gantman |
