如何在Java Spring中使控制器端点获取两个不同的对象? [英] How to make controller endpoint to get two different objects in java spring?
问题描述
我有一台用Java和spring构建的服务器.
I have a server built with java and spring.
我想做的是,具有相同端点的控制器将获得两个不同的对象.
What i am trying to do is that my controller with the same endpoint will get two different objects.
这是我的意思的示例:
我知道我可以做到:
public class Option1{
private String name;
...
//getter and setter
}
public class Option2{
private Long id;
...
//getter and setter
}
@Controller
public class Controller{
@RequestMapping(value = "service/getData/option1", method = RequestMethod.POST)
@ResponseBody
public String searchProv(@ResponseBody Option1 data1){
return "option1"
}
@RequestMapping(value = "service/getData/option2", method = RequestMethod.POST)
@ResponseBody
public String searchProv(@ResponseBody Option2 data2){
return "option2"
}
}
但是我想知道是否可以将不同的json对象传递到同一端点并做到这一点:
but I wonder if it is possible to passing different json object to the same endpoint and do that:
@Controller
public class Controller{
@RequestMapping(value = "service/getData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Any> getData(@ResponseBody Option1And2 data){
if(data instanceof Option1){
return return ResponseEntity<Any>(data.name,HttpStatus.OK)
}
if(data instanceof Option2){
return ResponseEntity<Any>(data.id,HttpStatus.OK)
}
return ResponseEntity<Any>("ok",HttpStatus.OK)
}
使得"Option1And2"是通用对象可以是option1或option2.
such that 'Option1And2' is generic object can be option1 or option2.
我试图将'Option1And2'替换为'Any',但操作不顺利,因为我得到了键和值的列表
I tried to replace 'Option1And2' to 'Any' but it didn't went well because I get a list of keys and values
推荐答案
您应使用 JsonNode 对象.
对于您的示例,您应该执行以下操作:
for your example you should do this:
@Controller
public class Controller{
@RequestMapping(value = "service/getData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Any> getData(@RequestBody JsonNode jsonNode){
ObjectMapper obj = new ObjectMapper();
if(jsonNode.has("name"){
Option1 result= obj.convertValue(jsonNode,Option1.class)
return ResponseEntity<Any>(result.name,HttpStatus.OK)
}
else {
Option2 result= obj.convertValue(jsonNode,Option2.class)
return ResponseEntity<Any>(result.id,HttpStatus.OK)
}
return ResponseEntity<Any>("ok",HttpStatus.OK)
}
您应该从此处导入的JsonNode和ObjectMapper:
the JsonNode and the ObjectMapper you should import from here:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.JsonNode;
此链接应该可以帮助您更好地了解JsonNode并为您提供更多详细信息.
this link should help you to understand better on JsonNode and give you more details.
和此链接应该可以帮助您实现从JsonNode到Java对象(POJO)的convertValue.
and this link should help you with the convertValue from JsonNode to java object(POJO).
这篇关于如何在Java Spring中使控制器端点获取两个不同的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!