Home > Blockchain >  Multiple nested exceptions while trying to consume JSON documents from API's
Multiple nested exceptions while trying to consume JSON documents from API's

Time:05-31

I've created a simple Spring Boot app, in which I am trying to consume an API through JSON information. Below you can see the simple code I created using RestTemplate on the Service Class. The problem I am facing is that when I am using the API url below, I am getting the following nested exception.

Nested Exception Received

In case I am using API url with less information, everything works fine. What am I doing wrong?

CONTROLLER CLASS

package com.andrekreou.iot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class RestSpringBootController {

    private final Service service;

    @Autowired
    public RestSpringBootController(Service service) {
        this.service = service;
    }

    @GetMapping(path = "/opap")
    public List<Object> getWeather(){
        return service.getWeather();
    }
}

SERVICE CLASS

package com.andrekreou.iot;

import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;

@org.springframework.stereotype.Service
public class Service {

    public List<Object> getWeather(){
        String url = "https://api.opap.gr/draws/v3.0/5104/last-result-and-active";
        RestTemplate restTemplate = new RestTemplate();
        Object[] weather = restTemplate.getForObject(url, Object[].class);
        return Arrays.asList(weather);
    }
}

CodePudding user response:

The problem is in this line of code:

 Object[] weather = restTemplate.getForObject(url, Object[].class);

You're mapping this JSON :

{
"last": {
"gameId": 5104,
"drawId": 2446,
"drawTime": 1653850800000,
"status": "results",
"drawBreak": 1800000,
"visualDraw": 2446,
"pricePoints": {
"amount": 0.5
},
"winningNumbers": {
"list": [
1,
9,
19,
22,
33
],
"bonus": [
1
]
},
...
}

Which is not array, it's an object, and that's why you are getting error described in your question.

Change above line of code to:

Object weather = restTemplate.getForObject(url, Object.class);

and it should work fine.

  • Related