How to Return JSON Data from Spring Controller Using @Responsebody

Returning JSON object as response in Spring Boot

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.

How to return JSON data from spring Controller using @ResponseBody

Add the below dependency to your pom.xml:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>

Spring MVC - How to return simple String as JSON in Rest Controller

Either return text/plain (as in Return only string message from Spring MVC 3 Controller) OR wrap your String is some object

public class StringResponse {

private String response;

public StringResponse(String s) {
this.response = s;
}

// get/set omitted...
}



Set your response type to MediaType.APPLICATION_JSON_VALUE (= "application/json")

@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)

and you'll have a JSON that looks like

{  "response" : "your string value" }

Returning JsonObject using @ResponseBody in SpringMVC

The answer is pretty simple when you realize there is no special HandlerMethodReturnValueHandler for the new JSR 353 API. Instead, in this case, the RequestResponseBodyMethodProcessor (for @ResponseBody) uses a MappingJackson2HttpMessageConverter to serialize the return value of your handler method.

Internally, the MappingJackson2HttpMessageConverter uses an ObjectMapper. By default, the ObjectMapper uses the getters of a class to serialize an object to JSON.

Assuming you are using Glassfish's provider implementation of the JSR 353, those classes are org.glassfish.json.JsonObjectBuilderImpl$JsonObjectImpl, org.glassfish.json.JsonStringImpl, and
org.glassfish.json.JsonNumberImpl, and javax.json.JsonValue$3 (an anonymous class for the value FALSE).

Because JsonObjectImpl (your result, ie. root, object) is a Map (special type), ObjectMapper serializes the map's entries as JSON key-value pair elements, where the Map key is the JSON key, and the Map value is the JSON value. For the key, it works fine, serializing as name, age, and married. For the value, it uses the classes I mentioned above and their respective getters. For example, org.glassfish.json.JsonStringImpl is implemented as

final class JsonStringImpl implements JsonString {

private final String value;

public JsonStringImpl(String value) {
this.value = value;
}

@Override
public String getString() {
return value;
}

@Override
public CharSequence getChars() {
return value;
}

@Override
public ValueType getValueType() {
return ValueType.STRING;
}
...
}

ObjectMapper therefore uses the Java Bean getters to serialize the JsonStringImpl object (that is the Map Entry's value), as

{"chars":"Dade","string":"Dade","valueType":"STRING"}

The same applies for the other fields.

If you want to correctly write the JSON, simply return a String.

@RequestMapping("/test", produces="application/json")
@ResponseBody
public String test() {
JsonObject result = Json.createObjectBuilder()
.add("name", "Dade")
.add("age", 23)
.add("married", false)
.build();
return result.toString();
}

Or make your own HandlerMethodReturnValueHandler, a little more complicated, but more rewarding.

Return JSON for ResponseEntityString

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
return "This is a String";
}

Spring Controller Return View and JSON Together

I presume in your first example you're actually returning "reports" rather than files. And if you want to return a view, you can't also return a response body - you can only return one thing.

So either you split it into two requests, or you put the JSON into the model, and retrieve it in the JSP, e.g.

Java:

ObjectMapper mapper = new ObjectMapper();
model.addAttribute("json", mapper.writeValueAsString(files));

JSP:

<script>
var files=${json};
</script>


Related Topics



Leave a reply



Submit