Home > OS >  how to get specific data from json JAVA SPRING?
how to get specific data from json JAVA SPRING?

Time:11-09

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 !

CodePudding user response:

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/

CodePudding user response:

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

  • Related