I have rest call something like this when I am getting result I am getting in string format something like this ,
public String getData(String value) throws ParseException {
final String url = "https://v1/supplier/suggest/{value}";
Map<String, String> params = new HashMap<String, String>();
params.put("value", value);
HttpEntity<?> httpEntity = new HttpEntity<>(this.getAuthHeaders());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> tpBody = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, params);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(tpBody.getBody());
JSONArray jsonArray = (JSONArray) json.get("data");
if (jsonArray.isEmpty()) {
System.out.println("No Data in JsonArray");
} else {
Object object = jsonArray.get(0);
System.out.println(object.toString());
}
}
}
Response:-
{"value":"DRAGON","datas":9.5}
Now from this string I want only datas field value , like suppose only 9.5
Any sort of help is appreciated .
CodePudding user response:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("data");
for (int i = 0; i < arr.length(); i ) {
String datas = arr.getJSONObject(i).getString("datas");
System.out.println(datas);
}
CodePudding user response:
The JSON response that you are getting is nothing but a Map. So I would suggest using the Jackson library to convert the json to a Map and then get the value for your key 'datas' - something like below:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(object.toString(),Map.class);
Double datasValue = (Double) map.get("datas");
Dependency for Jackson is:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>