Search code examples
javajsonspringgeneric-programming

How to make controller endpoint to get two different objects in 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.

This is an example for what I mean:

I know I can do that:

  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"
  }
}

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)
  }

such that 'Option1And2' is generic object can be option1 or option2.

I tried to replace 'Option1And2' to 'Any' but it didn't went well because I get a list of keys and values


Solution

  • 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<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)
         }
    

    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).