Spring MVC-Rest Controller에서 간단한 문자열을 JSON으로 반환하는 방법
내 질문은 본질적 으로이 질문에 대한 후속 조치 입니다.
@RestController
public class TestController
{
@RequestMapping("/getString")
public String getString()
{
return "Hello World";
}
}
위에서 스프링은 응답 본문에 "Hello World"를 추가 할 것이다. JSON 응답으로 문자열을 어떻게 반환합니까? 나는 따옴표를 추가 할 수 있지만 더 해킹처럼 느껴진다는 것을 이해합니다.
이 개념을 설명하는 데 도움이되는 예를 제공하십시오.
참고 : HTTP 응답 본문에 직접 작성하고 싶지는 않습니다. 문자열을 JSON 형식으로 반환하고 싶습니다 ( 응답이 유효한 JSON 형식 이어야 하는 RestyGWT 와 함께 Controller를 사용 하고 있습니다).
반환 text/plain
( Spring MVC 3 Controller에서 문자열 메시지 만 반환 에서와 같이 ) 또는 문자열을 객체로 감싸십시오.
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// get/set omitted...
}
응답 유형을 MediaType.APPLICATION_JSON_VALUE
(= "application/json"
)으로 설정하십시오.
@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
그리고 당신은 JSON처럼 보입니다
{ "response" : "your string value" }
JSON은 본질적으로 PHP 또는 JAVA 컨텍스트의 문자열입니다. 즉, 유효한 JSON 인 문자열을 응답으로 반환 할 수 있습니다. 다음과 같이 작동합니다.
@RequestMapping(value="/user/addUser", method=RequestMethod.POST)
@ResponseBody
public String addUser(@ModelAttribute("user") User user) {
if (user != null) {
logger.info("Inside addIssuer, adding: " + user.toString());
} else {
logger.info("Inside addIssuer...");
}
users.put(user.getUsername(), user);
return "{\"success\":1}";
}
간단한 문자열 응답에는 괜찮습니다. 그러나 복잡한 JSON 응답의 경우 Shaun에서 설명한대로 래퍼 클래스를 사용해야합니다.
한 프로젝트에서 JSONObject (maven dependency info )를 사용 하여이 문제를 해결했습니다 . 우리는 래퍼 객체가 아닌 간단한 문자열을 반환하는 것을 선호했기 때문에 이것을 선택했습니다. 새 종속성을 추가하지 않으려는 경우 내부 도우미 클래스를 대신 쉽게 사용할 수 있습니다.
사용법 예 :
@RestController
public class TestController
{
@RequestMapping("/getString")
public String getString()
{
return JSONObject.quote("Hello World");
}
}
당신은 쉽게 반환 할 수 JSON
와 String
속성에 response
다음과 같은
@RestController
public class TestController {
@RequestMapping(value = "/getString", produces = MediaType.APPLICATION_JSON_VALUE)
public Map getString() {
return Collections.singletonMap("response", "Hello World");
}
}
Simply unregister the default StringHttpMessageConverter
instance:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* Unregister the default {@link StringHttpMessageConverter} as we want Strings
* to be handled by the JSON converter.
*
* @param converters List of already configured converters
* @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(c -> c instanceof StringHttpMessageConverter)
.findFirst().ifPresent(converters::remove);
}
}
Tested with both controller action handler methods and controller exception handlers:
@RequestMapping("/foo")
public String produceFoo() {
return "foo";
}
@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
return e.getMessage();
}
Final notes:
extendMessageConverters
is available since Spring 4.1.3, if are running on a previous version you can implement the same technique usingconfigureMessageConverters
, it just takes a little bit more work.- This was one approach of many other possible approaches, if your application only ever returns JSON and no other content types, you are better off skipping the default converters and adding a single jackson converter. Another approach is to add the default converters but in different order so that the jackson converter is prior to the string one. This should allow controller action methods to dictate how they want String to be converted depending on the media type of the response.
I know that this question is old but i would like to contribute too:
The main difference between others responses is the hashmap return.
@GetMapping("...")
@ResponseBody
public HashMap<String, Object> endPointExample(...) {
HashMap<String, Object> rtn = new LinkedHashMap<String, Object>();
rtn.put("pic", image);
rtn.put("potato", "King Potato");
return rtn;
}
This will return:
{"pic":"a17fefab83517fb...beb8ac5a2ae8f0449","potato":"King Potato"}
Add produces = "application/json"
in @RequestMapping
annotation like:
@RequestMapping(value = "api/login", method = RequestMethod.GET, produces = "application/json")
Hint: As a return value, i recommend to use ResponseEntity<List<T>>
type. Because the produced data in JSON body need to be an array or an object according to its specifications, rather than a single simple string. It may causes problems sometimes (e.g. Observables in Angular2).
Difference:
returned String
as json: "example"
returned List<String>
as json: ["example"]
Add @ResponseBody
annotation, which will write return data in output stream.
In spring MVC 4 the default response type for objects is JSON. So all you need to do is wrap your String in some Object.
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// getters and setters
}
No modifications to the controller, except returning the StringResponse
instead of the String.
Make simple:
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
LOG.info("REST request health check");
return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
}
Add this annotation to your method
@RequestMapping(value = "/getString", method = RequestMethod.GET, produces = "application/json")
'programing tip' 카테고리의 다른 글
Java 열거 형에서 valueof () 및 toString () 재정의 (0) | 2020.07.25 |
---|---|
Anaconda에서 이전 패키지로 되돌리려면 어떻게합니까? (0) | 2020.07.25 |
공백 대신 탭을 삽입하도록 NetBeans를 구성하려면 어떻게해야합니까? (0) | 2020.07.25 |
Objective-C로 JSON을 구문 분석하는 방법은 무엇입니까? (0) | 2020.07.25 |
Knockout.js에서 관찰 가능한 바인딩을 지우거나 제거하는 방법은 무엇입니까? (0) | 2020.07.25 |