英文:
Returning JSON and XML using the same entity class
问题
以下是翻译好的部分:
我有这个控制器代码,它返回 XML,如何在实体类或控制器上添加最少的代码行或少量注解,使其返回 JSON?
@GetMapping(value = "/check", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseEntity<Result> getWapiResult(@RequestParam String sn){
return new ResponseEntity(
wapiService.getWapiData(sn).getBody(),
new HttpHeaders(),
HttpStatus.OK);
}
这是实体类
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Result {
private boolean complete;
private int srcsize;
private String urlpath;
}
英文:
I have this controller code that is returning XML , how can i make it return JSON with minimum line of code or just with few annotation on the entity class or the controller .
@GetMapping(value = "/check", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseEntity<Result> getWapiResult(@RequestParam String sn){
return new ResponseEntity(
wapiService.getWapiData(sn).getBody(),
new HttpHeaders(),
HttpStatus.OK);
}
This is the entity class
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Result {
private boolean complete;
private int srcsize;
private String urlpath;
}
答案1
得分: 2
需要更改控制器生成的内容:
@GetMapping(value = "/check", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Result> getWapiResult(@RequestParam String sn) {
return new ResponseEntity(
wapiService.getWapiData(sn).getBody(),
new HttpHeaders(),
HttpStatus.OK);
}
并且从实体中删除不必要的注解:
public class Result {
private boolean complete;
private int srcsize;
private String urlpath;
}
英文:
You need to change what controller produces
@GetMapping(value = "/check", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Result> getWapiResult(@RequestParam String sn){
return new ResponseEntity(
wapiService.getWapiData(sn).getBody(),
new HttpHeaders(),
HttpStatus.OK);
}
And remove unnecessary annotations from Entity
public class Result {
private boolean complete;
private int srcsize;
private String urlpath;
}
答案2
得分: 0
我猜测你的应用程序是使用Spring框架编写的。
在Controller中:@ResponseBody注解告诉控制器返回的对象会自动序列化为JSON并传递回HttpResponse对象。
所以,请只保留注解@ResponseBody。在@GetMapping中,只保留value。
@GetMapping(value = "/check")。
在实体类中:移除所有@XML注解。在Result类中保留一个无参数构造函数。
这将返回JSON作为ResponseBody。
英文:
I guess your application is in Spring.
On Controller: The @ResponseBody annotation tells the controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
So, keep annotation only @ResponseBody. In @Get Mapping, keep only value.
@GetMapping(value = "/check").
On Entity class: Remove all annotation of @XML. Keep a no-arg constructor in Result class.
This will return JSON as ResponseBody.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论