以下是从原始问题反序列化 JSON 的示例(在必要时进行了更正以确保有效性)。此示例还演示了如何配置 Jackson 以允许使用单引号 JSON 元素。
从最初的问题来看,我不明白尝试反序列化 JSON 的具体问题在哪里。对于简单的数据绑定,请注意 Java 属性名称必须与 JSON 元素名称匹配,并且 Java 数据结构必须与 JSON 数据结构匹配。
输入.json
{
'ruleId': 1000000,
'Formula':
{
'ruleAggregates': 'foo',
'fields': ['foo', 'foo'],
'Children':
[
{
'Formula':
{
'ruleAggregates': 'a',
'fields': ['1', '2'],
'Children': []
}
},
{
'Formula':
{
'ruleAggregates': 'b',
'fields': ['3', '4'],
'Children': []
}
},
{}
]
}
}
Java 对象模型
import com.fasterxml.jackson.annotation.JsonProperty;
class RuleModel
{
private long ruleId;
@JsonProperty("Formula") private Formula formula;
}
class Formula
{
private String ruleAggregates;
private List<String> fields;
private List<FormulaModel> Children;
}
class FormulaModel
{
@JsonProperty("Formula") private Formula formula;
}
JacksonFoo.java
import java.io.File;
import java.util.List;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
RuleModel model = mapper.readValue(new File("input.json"), RuleModel.class);
System.out.println(mapper.writeValueAsString(model));
}
}
输出:
{
"ruleId": 1000000,
"Formula": {
"ruleAggregates": "foo",
"fields": [
"foo",
"foo"
],
"Children": [
{
"Formula": {
"ruleAggregates": "a",
"fields": [
"1",
"2"
],
"Children": []
}
},
{
"Formula": {
"ruleAggregates": "b",
"fields": [
"3",
"4"
],
"Children": []
}
},
{
"Formula": null
}
]
}
}