How to call field of json in javafx/java

Rae Ian :

Currently I can call jsonplaceholder/albums API

using this code

 public class Main extends Application {

private static HttpURLConnection connection;
@Override
public void start(Stage primaryStage) throws Exception{

    BufferedReader reader;
    String line;
    StringBuffer responseContent = new StringBuffer();

    try {
        URL url = new URL("https://jsonplaceholder.typicode.com/albums");
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int status = connection.getResponseCode();

        if (status > 299){
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        }
        while((line = reader.readLine()) != null){
            responseContent.append(line);
        }

        reader.close();
        System.out.println(responseContent);

    }
    catch (MalformedURLException e){
        e.printStackTrace();
    }
    catch (IOException e){
        e.printStackTrace();
    } finally{
        connection.disconnect();
    }
} 

and this is the output

enter image description here

I can easily call the api. But the problem is how can I map each fields from this array?

In my code, I'm using responseContent to get json data.

I tried System.out.println(responseContent[2]); just to print only the title but It keeps giving me red line.

enter image description here

Adam :

responseContent is of type StringBuffer, this is just a utility for building Strings, that is arrays of characters. What you require is a JSON parser to provide an API to access the JSON string, e.g. to access the 2nd element in the array.

There are many libraries available, including Jackson, Gson, JSON simple, JSON-b etc.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422318&siteId=1