我使用Spring / Spring Boot和Spring MVC和@RestController
我有一个复合模型对象:
public abstract class BaseQuery {
private final Long characteristicId;
...
}
public abstract class ComparableQuery extends BaseQuery {
private final Object value;
private final String comparisonOperator;
...
}
public class GreaterOrEqualQuery extends ComparableQuery {
public GreaterOrEqualQuery(Long characteristicId, Object value) {
super(characteristicId, value, ">=");
}
}
public class EqualQuery extends ComparableQuery {
public EqualQuery(Long characteristicId, Object value) {
super(characteristicId, value, "=");
}
}
public class GreaterQuery extends ComparableQuery {
public GreaterQuery(Long characteristicId, Object value) {
super(characteristicId, value, ">");
}
}
public class CompositQuery extends BaseQuery {
private final String operator;
private final BaseQuery[] queries;
public CompositQuery(Long characteristicId, Operator operator, BaseQuery... queries) {
super(characteristicId);
this.operator = operator.value;
this.queries = queries;
}
...
}
等
此模型的示例用法类似于:
Set<BaseQuery> queries = new HashSet<>();
BaseQuery megapixelCharacteristicQuery = new CompositQuery(megapixelCharacteristic.getCharacteristicId(), CompositQuery.Operator.AND, new GreaterOrEqualQuery(megapixelCharacteristic.getCharacteristicId(), 10), new LessOrEqualQuery(megapixelCharacteristic.getCharacteristicId(), 50));
queries.add(megapixelCharacteristicQuery);
queries.add(new EqualQuery(androidCharacteristic.getCharacteristicId(), true));
Set<BaseQuery> queries
的序列化JSON对象如下所示:
[
{
"operator":"AND",
"queries":[
{
"value":10,
"comparisonOperator":"\u003e\u003d",
"characteristicId":391
},
{
"value":50,
"comparisonOperator":"\u003c\u003d",
"characteristicId":391
}
],
"characteristicId":391
},
{
"value":true,
"comparisonOperator":"\u003d",
"characteristicId":383
}
]
我必须将此类或类似的JSON从客户端应用程序(AngularJS)传递到我的后端REST API端点,以便获得如上所述的正确反序列化模型(使用CompositQuery
或{{1}等相应条目进行设置})。
现在我的Rest控制器上的Spring应用程序后端逻辑无法使用适当的类正确地反序列化此JSON。
Spring中是否有任何方法可以为此JSON提供一些元信息(或其他内容)以帮助Spring正确反序列化此结构?
答案 0 :(得分:5)
你可以使用超类上的jackson注释来实现这一点,如下所示:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "javaclass")
@JsonSubTypes({
@Type(value = GreaterOrEqualQuery.class),
@Type(value = EqualQuery.class)
//and so on...
})
public abstract class BaseQuery {
...
}
这会将javaclass
属性添加到json表示中,这是use = JsonTypeInfo.Id.CLASS
的完全限定名称。为了简化此属性的值,请考虑use
的{{1}}参数的不同选项(例如@JsonTypeInfo
)。