As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.
And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001
If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.
Answer from prem kumar on Stack OverflowAs you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.
And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001
If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.
The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject. If you want to create a dynamic JSON structure, you can use a Map, for example:
@GetMapping
public Map<String, String> sayHello() {
HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
map.put("foo", "bar");
map.put("aa", "bb");
return map;
}
This will lead to the following JSON response:
{ "key": "value", "foo": "bar", "aa": "bb" }
This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode and ArrayNode. To use it, you have to autowire ObjectMapper in your service/controller. Then you can use:
@GetMapping
public ObjectNode sayHello() {
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("key", "value");
objectNode.put("foo", "bar");
objectNode.put("number", 42);
return objectNode;
}
This approach allows you to add child objects, arrays, and use all various types.
How to output response in JSON format ? newbie Spring boot here
java - How to return JSON response in Springboot? - Stack Overflow
java - Return JSON object from a spring-boot rest Controller - Stack Overflow
How to convert object to json in controller?
Videos
Hey I want my service to return something like :
{
"location1": {
"postal_code": "AB12 3CD",
"latitude": 51.12345,
"longitude": -0.67890
},
"location2": {
"postal_code": "EF45 6GH",
"latitude": 52.23456,
"longitude": -1.78901
},
"distance": 123.45,
"unit": "km"
}so my service supposed to be calculate distance between two locations and display response as above. How to create the service and restcontroller method?
Do we need to use Map<String, Object> in service method to output the response? please guide me
You can simply return an object with those attributes. For example declare a new class that represents your desired response:
public class UserResponse {
private Boolean status;
private String message;
private List data;
public UserResponse(){
}
// setters & getters
}
And then change your controller:
@GetMapping("/users")
public UserResponse getAllUsers() {
List<User> user = repository.findAll(); // get all users from db
UserResponse userResponse = new UserResponse();
userResponse.setStatus(true);
userResponse.setMessage("Data is found");
userResponse.setData(user);
return userResponse;
}
For an in depth explanation of what was wrong with your approach you can check this answer
You can use the following way, so that you respond any data you want. I have been using this for long time.
public class ApiResponse {
private boolean status;
private String message;
private Object data;
private ErrorCode errorCode;
//use constructors instead of setters
//getters
}
If you are using the spring-boot-starter-web,
your project is already set to return JSON.
Instead of String as the return value from checkEmailUnique,
use an object type that you create.
Here is an example:
public class EmailStatusCheckJson
{
private Boolean emailIsAvailable;
public Boolean getEmailIsAvailable()
{
return emailIsAvailable;
}
public void setEmailIsAvailable(
final Boolean newValue)
{
emailIsAvailable = newValue
}
}
@RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
public EmailStatusCheckJson checkEmailUnique(@RequestBody final String username)
{
final EmailStatusCheckJson returnValue = new EmailStatusCheckJson();
if (...) // email is available.
{
returnValue.setEmailIsAvailable(true);
}
else
{
returnValue.setEmailIsAvailable(false);
}
return returnValue;
}
Edited added more example.
Rest method have a return type as String .In place of any String you can use a user defined object where(inside there) put a boolean variable e.g. status there you can send whether the username is present or not. According to the response from the rest side you can forward towards angular.
My project uses spring data embers for auditing and I would like users to be able to see the data in the auditing table using a controller endpoint. So something like “/audit/2” would give produce a JSON array with the auditing history of the model object that has an id of 2.
My repository class extends RevisionRepository and gives me some methods I can work with like findRevisions(id).
My question is how do I convert the output of this method (which is a Revision object) into a JSON array? Do I need a DTO to manually get its fields from the Revision object or is there an easier way?