JoeyOC
JoeyOC

Reputation: 133

GET JSON response, parse it and then convert back to a JSON

My goal is;

  1. GET a JSON file from an API and make changes to the data
  2. Then generate a new dictionary from this data
  3. 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

Upvotes: 0

Views: 1296

Answers (2)

Michael Gantman
Michael Gantman

Reputation: 7792

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

Upvotes: 0

Rob Spoor
Rob Spoor

Reputation: 9090

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.

Upvotes: 1

Related Questions