How to make controller endpoint to get two different objects in java spring?

后端 未结 3 655
臣服心动
臣服心动 2021-01-03 05:50

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.

This is an ex

3条回答
  •  春和景丽
    2021-01-03 06:39

    You should use JsonNode object.

    for your example you should do this:

     @Controller
     public class Controller{
    
     @RequestMapping(value = "service/getData", method = RequestMethod.POST)
     @ResponseBody
     public ResponseEntity getData(@RequestBody JsonNode jsonNode){
    
       ObjectMapper obj = new ObjectMapper();
    
      if(jsonNode.has("name"){
       Option1 result= obj.convertValue(jsonNode,Option1.class)
      return ResponseEntity(result.name,HttpStatus.OK)
        }    
    
       else {
    
       Option2 result= obj.convertValue(jsonNode,Option2.class)
       return ResponseEntity(result.id,HttpStatus.OK)
        }
    
        return ResponseEntity("ok",HttpStatus.OK)
         }
    

    the JsonNode and the ObjectMapper you should import from here:

    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.databind.JsonNode;
    

    this link should help you to understand better on JsonNode and give you more details.

    and this link should help you with the convertValue from JsonNode to java object(POJO).

提交回复
热议问题