🏡环境

SpringBoot + lombok

📋遇到需求

大概意思

给出一个参数通过URI接收一个对象test(可能是两种类的对象)和一个type(判断test类型)

🌌假设:

如果type为0,test为TestTest对象,

如果type为1,test为TestTest2对象

🔬实现过程:

TestTest.class和TestTest2.class

  1. @Data
  2. @Accessors(chain = true)
  3. public class TestTest {
  4. String abc;
  5. String aaa;
  6. TestTest2 test2;
  7. }
  8. @Data
  9. @Accessors(chain = true)
  10. public class TestTest2 {
  11. String ddd;
  12. String ccc;
  13. }

Controler

  1. @RestController
  2. @RequestMapping("/api/v1")
  3. public class TestController {
  4. private final Logger log = LoggerFactory.getLogger(TestController.class);
  5. @PostMapping("/hello")
  6. public String helloWorld(String type,
  7. @RequestBody Object test) throws IOException {
  8. log.info("test {}", test.toString());
  9. if (type.equals("0")) {
  10. TestTest testTest = new TestTest();
  11. ObjectMapper objectMapper = new ObjectMapper();
  12. String testString = objectMapper.writeValueAsString(test);
  13. testTest = objectMapper.readValue(testString, TestTest.class);
  14. return testTest.toString();
  15. }else if (type.equals("1")){
  16. TestTest2 testTest2 = new TestTest2();
  17. ObjectMapper objectMapper = new ObjectMapper();
  18. String testString = objectMapper.writeValueAsString(test);
  19. testTest2 = objectMapper.readValue(testString, TestTest2.class);
  20. return testTest2toString();
  21. }
  22. return "error";
  23. }
  24. }