Hi I am hitting an endpoint with rest template and getting the response.
When I use String as return type and print the response it's an XML response with multiple tags.
and when I use Object as return type then RestTemplate is mapping only last tag from the list.
With String.class as return type
Request:
ResponseEntity<String> response = restTemplate.postForEntity(urlTemplate, httpEntity, String.class);
System.out.println(response.getBody());
Response:
<Order>
<OrderLines>
<OrderLine LineID="1"></OrderLine>
<OrderLine LineID="2"></OrderLine>
<OrderLine LineID="3"></OrderLine>
</OrderLines>
</Order>
With Object.class as return type
Request:
ResponseEntity<Object> response = restTemplate.postForEntity(urlTemplate, httpEntity, Object.class);
System.out.println(response.getBody());
Response:
{
"OrderLines": {
"OrderLine": {
"LineID": "3"
}
}
}
Expected Response with Object.class as return type is:
{
"OrderLines": {
"OrderLine": [
{
"LineID": "1"
},
{
"LineID": "2"
},
{
"LineID": "3"
}
]
}
}
Please suggest the solution to this.
You can create a model class to Map the expected Response with Object.class as return type, But instant you will need to have it like OrderLines.class ( which is your newly created model )
Then you can use ObjectMapper or Gson to map the response like the following.
OrderLines obj = gson.fromJson(stringResponse, OrderLines.class);
return obj;
This will have the created model object to be returned after getting the information needed from the string returned type.
Related
I am getting below response when I am calling an API.
Response postRequestResponse = ConnectionUtil.getwebTarget()
.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
.path("bots")
.path(ReadSkillID.readSkillId())
.path("dynamicEntities").path(dynamicEntityID)
.path("pushRequests").path(pushRequestID).path(operation)
.request()
.header("Authorization", "Bearer " + ConnectionUtil.getToken())
.get();
Below output I am getting.
{
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I have to return this output to client with an additional field in the response. How can modify the above response and make it
{
"EntityName": "NewEntity", //New field
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I am adding this additional field here
"EntityName": "NewEntity"
How can I do that. many things I tried but got exception.
get JSON from postRequestResponse (i have no idea what framework you are using, so you have to figer it out on your own, but the Response datatype will probably have a getResponseBody or similar method returing the JSON)
add EntityName
serialize it again to json.
class YourBean {
#Autowired
private ObjectMapper objectMapper;
public void yourMethod() {
// 1
final InputStream jsonFromResponse = ...
// 2
Map dataFromResponse = objectMapper.readValue(jsonFromResponse, Map.class);
dataFromResponse.put("EntityName", "NewEntity");
// 3
final String enrichedJson = objectMapper.writeValueAsString(dataFromResponse);
}
}
enrichedJson contains EntityName and whatever comes from the API.
I am trying to make API POST Request with WebClient in Spring Boot. But I cannot to make a request and receive response as JSONObject. With RestTemplate I did it, recently I started to learn WebClient. So that I got stuck.
Error Spring gives:
Error:(48, 28) java: incompatible types: no instance(s) of type variable(s) T exist so that reactor.core.publisher.Mono conforms to org.json.simple.JSONObject
Here is my source code:
Controller.java
JSONObject jsonObject = new JSONObject();
Turnover turnover = new Turnover();
JSONObject resp = webClientBuilder.build()
.post()
.uri("http://180.12.10.10:8080/turnover/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON )
.body(Mono.just(turnover),Turnover.class)
.retrieve()
.bodyToMono(JSONObject.class);
Turnover.java
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Turnover {
private String start_date;
private String end_date;
private String account;
public Turnover(){
setStart_date("01.01.2020");
setEnd_date("01.06.2020");
setAccount("20296");
}
}
Json I want to send
{
"start_date":"01.01.2020",
"end_date":"01.06.2020",
"account":"20296"
}
Response API Returns:
{
"status": 1,
"message": "success",
"data": [
{
"CODE_ACCOUNT": "20296",
"CREDIT": 60610187386.86,
"DEBIT": 60778253872.1
}
]
}
Any Help is appreciated!
Most likely the issue is that you're asking for a string back but assigning it to a JSONObject. The exception seems odd and I'd expect a compilation error with what you have but try this:
.bodyToMono(JSONObject.class)
.block();
And you'll need to fix the content type on the request to be MediaType.APPLICATION_JSON so that it passes your object as json.
I am trying to pass multi-valued parameters in request param and expecting results as below. I am using #RequestParam List<String> in the controller to return multi-valued parameters but I am trying to figure how can return the list of employee details in the response as shown below.
Http Request: /list/id?employee_ids=E123,E765
I am getting below response:
{
"Employees": [
{
"EmployeeID": "E123,E765",
"EmployeeName": "John"
}
Expected Results:
{
"Employees": [
{
"EmploeeId": "E123",
"EmployeeName": "John"
},
{
"EmploeeId": "E765",
"EmployeeName": "Peter"
}
]
}
Pojo:
private String employeeId;
private String employeeName;
Service:
When a list of employee id's are passed, I should get employee id and name
'Employee table contains: EmployeeId and EmployeeName as columns'
Controller:
#GetMapping(value = "/id")
public ResponseEntity<EmployeeResponse> getEmployee(#RequestParam List<String> employee_ids , #RequestHeader Map<String, Object> headers) {
log.info("Received request with headers: {}", headers);
ResponseEntity<EmployeeResponse> response = ResponseEntity.ok(getEmployee.employees(employee_ids
));
log.info("Responding to request with response: {}", response);
return response;
Here is an example of how I use hashmaps in my routes:
Map<String, Object> pdata = new HashMap();
pdata.put("schedules", schedSVC.getSchedules());
pdata.put("webuser", userSVC.getActiveUser());
if you are using JdbcTemplate
use the NamedParameterJdbcTemplate object
then you have the method NamedParameterJdbcTemplate.queryForList(query, params);
just need to add the query with the relevant list
I am currently working on a project where i need to make a rest call to an external API and parse the JSON response to a POJO and return back the POJO as JSON for another rest request. I am able to parse the JSON response, but my requirement is to parse only one particular node from it. How can i achieve this? I am using Spring Boot and Spring Rest Template to make the external rest call. Please help!!!
#RestController
public class ProductsController {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductsController.class);
#RequestMapping(value = "/myRetail/product/{id}", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE })
#ResponseBody
public Item getSchedule(#Valid Payload payload) {
String URL = "<External API>";
LOGGER.info("payload:{}", payload);
Item response = new Item();
RestTemplate restTemplate = new RestTemplate();
Item item = restTemplate.getForObject(URL, Item.class);
LOGGER.info("Response:{}", item.toString());
return response;
}
}
JSONResponse (This is a part of whole i receive)
{
"ParentNode": {
"childNode": {
"att": "13860428",
"subchildNode 1": {
"att1": false,
"att2": false,
"att3": true,
"att4": false
},
"att4": "058-34-0436",
"att5": "025192110306",
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
},
............
}
Required JSONpart from the above whole response:
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
Use the org.json library. With this library you can parse the payload to a JSONObject and navigate to your required subpart of the document.
So you have to get the payload as a JSON-String and parse it to the JSONObject from the library. After that you can navigate to your required subpart of the document and extract the value and then parse it to your required Java POJO.
Have look at: How to parse JSON
Just map the path to the needed object:
{
"ParentNode": {
"childNode": {
"subchildenode2": {
"att6": "hello",
"att7": ["how are you", "fine", "notbad"],
"is_required": "yes"
}
}
}
And then simply:
Response responseObject= new Gson().fromJson(json, Response.class);
SubChildNode2 att6 = responseObject.getParentNode().getChildNode().getSubChildNode2();
I have added Dependency for Gson in pom.xml
public ResponseEntity<String> findSearchInfo(#RequestParam String searchName)
{
ResponseEntity<String> response = gasRESTTemplate
.getForEntity(uri,String.class);
Gson gson = new Gson();
response = gson.toJson(response);
return response;
}
uri is returning me a HashMap which I want to convert to JSON.So I have used Gson's toJson method.Now the problem is that method is returning me json but i am unable to assign it to response cause it's type is ResponseEntity which is compulsory.
So what should I do to return that json by response?
Because of this I am getting error
required: org.springfremwork.http.ResponseEntity<java.lang.String>
found: java.lang.String
I know return type is ResponseEntity
So How should I initialize that JSON to response variable.
What about using this constructor (source) :
ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
ResponseEntity<String> response =
new ResponseEntity(gson.toString(),
new MultiValueMap(),
HttpStatus.OK);