gpt4 book ai didi

java - 如何将 @RestController 中的请求主体转换为抽象值列表?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:07 27 4
gpt4 key购买 nike

假设我们有以下类:

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

如何将 json 绑定(bind)或转换为 List<Investment> 的请求正文不使用 jackson 的 @JsonSubTypes在抽象类上 Investment , 而是使用 InvestmentFactory

最佳答案

@JsonDeserialize 效果很好,但如果您的字段不仅仅是类型,那么您将不得不手动设置它们。如果你要回到 jackson ,你可以使用:

投资类

    @JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "investmentType")
@JsonTypeIdResolver(InvestmentResolver.class)
public abstract class Investment {
}

InvestmentResolver.class

public class InvestmentResolver extends TypeIdResolverBase {

@Override
public JavaType typeFromId(DatabindContext context, String id) throws IOException {
Investment investment = InvestmentFactory.getTypeFromString(type);
return context.constructType(investment.getClass());
}

这样做的美妙之处在于,如果您开始向 Investment 添加字段,则不必将它们添加到 Desrializer 中(至少,在我的情况下,这发生在我身上),而是 Jackson 会为您处理.所以明天你可以有测试用例:

'[{"investmentType":"Bond","investmentName":"ABC"},{"investmentType":"Equity","investmentName":"APPL"}]'

你应该可以开始了!

关于java - 如何将 @RestController 中的请求主体转换为抽象值列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302616/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com