假设我们有以下控制器
@Controller
@RequestMapping("/Index")
public class ControllerClass {
@RequestMapping("/Result")
@ResponseBody
public List<Integer> result(){
List<Integer> result = new ArrayList<Integer>();
result.add(1);
result.add(2);
return result;
}
}
现在我想存储URL&#34; / Index / Result&#34;的JSON结果。成一个字符串。或者简单地说,在应用注释后存储控制器的JSON结果。请注意,它不适用于为此目的考虑的测试和Web服务问题。有什么想法吗? 提前谢谢。
答案 0 :(得分:1)
您可以将杰克逊的ObjectMapper注入控制器,以便在通过ResponseEntity返回之前手动将结果序列化为JSON
。
@Configuration
public class Config {
@Bean
public ObjectMapper objectMapper() {
// returning a plain ObjectMapper,
// you can change this to configure the ObjectMapper as requiered
return new ObjectMapper();
}
}
@Controller
@RequestMapping("/Index")
public class ControllerClass {
@Autowired
private ObjectMapper objectMapper;
@RequestMapping(value="/Result",
method=RequestMethod.GET,
produces="application/json")
@ResponseBody
public ResponseEntity<String> result(){
List<Integer> result = new ArrayList<Integer>();
result.add(1);
result.add(2);
String jsonResult = objectMapper.writer().writeValueAsString(result);
// here you can store the json result before returning it;
return new ResponseEntity<String>(jsonResult, HttpStatus.OK);
}
}
修改强>:
您还可以尝试定义HandlerInterceptor,以捕获您感兴趣的请求的响应正文。
@Component
public class RestResponseInterceptor implements HandlerInterceptor {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// inspect response, etc...
}
}
答案 1 :(得分:0)
我建议将jackson依赖项放在你的pom.xml中,如果它们还没有。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
您还可以像这样更新您的请求映射
@RequestMapping(value = "/Result", produces = "application/json;charset=utf-8")