I trying to send a post request with json data in a particular format using Spring boot. I am not getting data in expected format. Please help e resolve it. Thanks in advance.
class UserService{
public void sendRequest(User data){
HttpHeaders header = new HttpHeaders();
mapHeaders.set("Content-Type","application/json");
Map<String,User> m= new HashMap<String,User>();
m.put("request",data);
//print m i.e. payload being sent
HttpEntity entity = new HttpEntity<Object>(m, header);
String url = some url here
ResponseEntity<Object> response = restTemplate.exchange(url, httpMethod, entity,
Object.class);
}
}
class User{
private String firstName;
private String lastName;
}
While printing payload it displays payload as:
{request=User(firstName=Raj,lastName=Kumar)}
I want the data as
{request={firstName=Raj,lastName=Kumar}}
CodePudding user response:
Do as below using Jackson library in case you need to print an object in JSON format:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
...
m.put("request", data);
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonString = objectMapper.writeValueAsString(m);
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
...
CodePudding user response:
You can use JSONObject :
Map<String, JSONObject> m = new HashMap<>();
m.put("request", new JSONObject(data));
Result :
{request={"firstName":"Raj","lastName":"Kumar"}}
Maven dependency :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>