How to capture a json field in java?

Asked

Viewed 101 times

-1

I have that code:

public static void main(String[] args) throws JSONException {
    String filmes[] = new String[2];

    RestTemplate restTemplate = new RestTemplate();
    String resposta = restTemplate.getForObject("https:api.....", String.class);

    String resFormatada = resposta.replace("[","");

    JSONObject jsonObject = new JSONObject(resFormatada);
    for (int i = 0; i<3; i++) {
        filmes[i] = jsonObject.getString("id");
        System.out.println(filmes[i]);
    }
}

The return of the api is:

[{"id":"tt3606756","titulo":"Os Incríveis 2","ano":2018,"nota":8.5},{"id":"tt4881806","titulo":"Jurassic World: Reino Ameaçado","ano":2018,"nota":6.7},{"id":"tt5164214","titulo":"Oito Mulheres e um Segredo","ano":2018,"nota":6.3}]

I would like to save each ID in a vector, but the way I do I’m only getting the first one and not all 3. Someone could help me.

1 answer

0


The problem is using one JSONObject just instead of using JSONArray as you receive an array and not just an object. By changing the code you get the following.

public static void main(String[] args) throws JSONException {
    RestTemplate restTemplate = new RestTemplate();
    String resposta = restTemplate.getForObject("https:api.....", String.class);

    JSONArray jsonArray = new JSONArray(resposta);
    String[] filmes = new String[jsonArray.length()];

    for (int i = 0; i < jsonArray.length(); i++) {
        filmes[i] = jsonArray.getJSONObject(i).getString("id");
        System.out.println(filmes[i]);
    }
}
  • Thank you, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.