【笔记】SpringBoot项目请求参数动态类型

前言

SpringBoot项目请求参数动态类型

正文

com.controller.DemoController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import com.bean.BaseType;
import com.bean.TypeDouble;
import com.bean.TypeInt;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

@RequestMapping("/")
public String hello(@RequestBody BaseType dto) {
if (dto instanceof TypeInt typeInt) {
return "TypeInt: " + typeInt.getD();
} else if (dto instanceof TypeDouble typeDouble) {
return "TypeDouble: " + typeDouble.getD();
} else {
return "0";
}
}

}
com.bean.DemoController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "t")
@JsonSubTypes({
@JsonSubTypes.Type(value = TypeInt.class, name = "I"),
@JsonSubTypes.Type(value = TypeDouble.class, name = "D")
})
public class BaseType {

@JsonProperty("t")
private String t;

}
com.bean.DemoController.java
1
2
3
4
5
6
7
8
9
10
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class TypeInt extends BaseType {

@JsonProperty("d")
private Integer d;

}
com.bean.DemoController.java
1
2
3
4
5
6
7
8
9
10
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class TypeDouble extends BaseType {

@JsonProperty("d")
private Double d;

}

完成