Spring MVC - How to Return Simple String as JSON in Rest Controller

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" }

Simple string as JSON return value in spring rest controller

When you return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.

spring mvc restcontroller return json string

It turns out that when you use the @EnableWebMvc annotation that it turns on a bunch of http message converters by default. The second one in the list is the StringHttpMessageConverter which the documentation says will be applied for text/* content types. However, after stepping through with the debugger, it applies to String objects for */* content types- which obviously includes application/json.

The MappingJackson2HttpMessageConverter which is responsible for application/json content types is further down on this list. So for Java objects other than String, this one gets called. That's why it was working for Object and Array types, but not String- despite the good suggestions of using the produces attribute to set application/json content type. Although that content type is necessary to trigger this converter, the String converter was grabbing the job first!

As I was extending the WebMvcConfigurationSupport class for some other configuration, I overrode the following method to put the Jackson converter first so when the content-type is application/json then this one will be used instead of the String converter:

@Override
protected void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
// put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON
converters.add(new MappingJackson2HttpMessageConverter());
// and probably needs a string converter too for text/plain content-type strings to be properly handled
converters.add(new StringHttpMessageConverter());
}

Now when I call the test method from curl I get the desired "test" output instead of just test, so the angular client which is expecting JSON is now happy.

There is a clean way to return string as json in a Spring Web API?

Yes,you can use libraries like gson or jackson to convert your strings into JSON, there by giving you a json output like below.

Gson gson= new GsonBuilder().create();
gson.toJson(Your String);

Also, dont forget to add
produces = MediaType.APPLICATION_JSON_VALUE to the method exposed so that spring knows what kind of o/p needs to be produced.

Return JSON for ResponseEntityString

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

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 string to json format

You can try this

    if (id == null) {
message = "{\"message\":\"login fail\"}";

} else {
message = "{\"message\":\"login Successfully\"}";
}

Or if you want response in plain text, you can use :-

produces=MediaType.TEXT_PLAIN_VALUE

Hope this may help you.



Related Topics



Leave a reply



Submit