假设我们有以下类:
public abstract class Investment {
private String investmentType;
// getters & setters
}
public class Equity extends Investment {
}
public class Bond extends Investment {
}
public class InvestmentFactory {
public static Investment getTypeFromString(String investmentType) {
Investment investment = null;
if ("Bond".equals(investmentType)) {
investment = new Bond();
} else if ("Equity".equals(investmentType)) {
investment = new Equity();
} else {
// throw exception
}
return investment;
}
}
以下@RestController:
@RestController
public class InvestmentsRestController {
private InvestmentRepository investmentRepository;
@Autowired
public InvestmentsRestController(InvestmentRepository investmentRepository) {
this.investmentRepository = investmentRepository;
}
@RequestMapping(RequestMethod.POST)
public List update(@RequestBody List investments) {
return investmentRepository.update(investments);
}
}
以及请求体中的以下json:
[
{"investmentType":"Bond"},
{"investmentType":"Equity"}
]
如何将json绑定或转换为List< Investment>的请求主体?没有在抽象类投资上使用Jackson的@JsonSubTypes,而是使用InvestmentFactory?