将 JSON 反序列化为类
2022-09-03 14:08:41
服务器返回 JSON 的以下部分:
{"condition": {
"or": [
{
"and": [
{
"operand": "a",
"operator": "==",
"value": "true"
},
{
"not": {
"operand": "b",
"operator": "==",
"value": "true"
}
}
]
},
{
"and": [
{
"operand": "b",
"operator": "==",
"value": "true"
},
{
"not": {
"operand": "a",
"operator": "==",
"value": "true"
}
}
]
}
]
}}
我写了下一个类层次结构:
public interface Condition {}
public class Expression implements Condition {
public Expression(String operator, String operand, String value) {
}
}
public class Not implements Condition {
public Not(Condition condition) {
}
}
public abstract class GroupOperation implements Condition {
public GroupOperation (List<Condition> conditions) {
}
}
public class And extends GroupOperation {
public And(List<Condition> conditions) {
}
}
public class Or extends GroupOperation {
public Or(List<Condition> conditions) {
}
}
我已经添加了下一个jackson注释,希望能反序列化上面的JSON:
@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(value=Not.class, name="not"),
@JsonSubTypes.Type(value=And.class, name="and"),
@JsonSubTypes.Type(value=Or.class, name="or"),
@JsonSubTypes.Type(value=Expression.class, name=""),
})
我将适当的构造函数标记为 .@JsonCreator
这不适用于类。Expression
如果我修改JSON,每个对象都有名称“表达式”:expression
"expression" : {
"operand": "a",
"operator": "==",
"value": "true"
}
和
@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(value=Not.class, name="not"),
@JsonSubTypes.Type(value=And.class, name="and"),
@JsonSubTypes.Type(value=Or.class, name="or"),
@JsonSubTypes.Type(value=Expression.class, name="expression"),
})
当尝试解析“not”条件时,它失败,该条件说“无法实例化抽象类需要有关类型的更多信息”。所以看起来它在更深入的解析中丢失了注释声明。
我想知道是否有可能用jackson为原始JSON编写反序列化
为什么第二种方法不适用于反序列化
Not