猿问

如何将 @RestController 中的请求正文转换为抽象值列表?

假设我们有以下类:


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<Investment> update(@RequestBody List<Investment> investments) {

       return investmentRepository.update(investments);

    }


}

以及请求正文中的以下 json:


[

  {"investmentType":"Bond"},

  {"investmentType":"Equity"}

]

如何在List<Investment> 不使用 Jackson 的@JsonSubTypes抽象类的情况下将 json 绑定或转换为请求正文Investment,而是使用InvestmentFactory?


慕丝7291255
浏览 168回答 4
4回答
随时随地看视频慕课网APP

相关分类

Java
我要回答