1

In the company that I work they gave me the task of connecting to an API about the actual dollar value and obtaining data from it. I got it but i get a JSON with too many data and i just need the dollar value:

JSON i get

If you can't see the screenshot this is the JSON i get

{
"version": "1.7.0",
"autor": "mindicador.cl",
"codigo": "dolar",
"nombre": "Dólar observado",
"unidad_medida": "Pesos",
"serie": [
    {
        "fecha": "2021-11-08T03:00:00.000Z",
        "valor": 812.4
    }
]
}

I just need to get

"valor": 812.4

This is how i call the API in JAVA code

@Service
public class DolarServiceImp implements DolarService{
@Autowired

private RestTemplate restTemplate;

@Override
public String getDolar() {
    
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

    String url = "https://mindicador.cl/api/dolar/08-11-2021";

    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
    
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

     return response.getBody(); 
    
}
}

I think getBody function get all the data. I have tried all day to get results but nothing, my head is going to explode. Thanks in advance !

2 Answers 2

2

If you just need a single value from json instead a complete java bean mapping, you could use jsonpath

RestTemplate restTemplate = new RestTemplate();
String json  = restTemplate.getForObject("https://api.com/foo", String.class);
String jsonPathExpression = "$.serie[0].valor"; 
Double valor = JsonPath.parse(json).read(jsonPathExpression, Double.class);

With jsonpath you could query any value from json without map field by field to a java bean/pojo:

$.store.book[?(@.price < 10)]

You could use this web to test your jsonpath expression:

https://jsonpath.com/

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the JSONObject like this :

.
.
.
 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

 JSONObject bodyJson = new JSONObject(response.getBody()); 
      
 JSONObject serie =(JSONObject)bodyJson.getJSONArray("serie").get(0);
 Double dollarVal = serie.getDouble("valor");

 return "valor:" + dollarVal;
}

That will get you "valor": 812.4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.