as input. Spring Boot automatically converts it into a POJO. However, the JSON that I have has the following structure.
{
"strategy": "STRATEGY_NAME",
"data" : {}
}
The problem is, depending on the strategy, the data object will change. Any way to handle this?
Your DTOs for each strategy have to extend from same base class, at least that "strategy" property. Otherwise you would end up writing your controller to accept Object param. So you have basically several options: - use @JsonComponent to register your custom codec, the most low-level solution - use jackson annotations, here's nice article I've just found, @JsonDeserialize and @JsonDeserialize are low-level variants of @JsonComponent - use jackson polymorphism support (again that nice article has it described https://www.baeldung.com/jackson-annotations#jackson-polymorphic-type-handling-annotations) - rethink your api design, and maybe you actually don't want dive into polymorphism; this may be the case if that number of strategies is huge, and/or there are not strict and clear boundaries between those strategies; in that case jackson has nice @JsonAnySetter which is exactly for this case
Well, to be less ambiguous. If you're 100% sure about your api, then in your exact case I would suggest using jackson polymorphic stuff (@JsonTypeInfo, @JsonSubType etc). Other options are nice to know, but polymorpic jackson annotations suit best for that particular case
Обсуждают сегодня