gpt4 book ai didi

java - 如何获取映射 URL 的 JSON 结果

转载 作者:行者123 更新时间:2023-12-01 12:34:29 26 4
gpt4 key购买 nike

假设我们有以下 Controller

@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“/Index/Result”的 JSON 结果存储到字符串中。或者简单地,在应用注释后存储 Controller 的 JSON 结果。请注意,它不适用于为此目的考虑的测试和网络服务问题。有什么想法吗?提前致谢。

最佳答案

你可以注入(inject) Jackson 的 ObjectMapper进入 Controller 以手动将结果序列化为 JSON,然后再通过 ResponseEntity 返回.

@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...
}
}

关于java - 如何获取映射 URL 的 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25700872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com