以下是从原来的问题反序列化JSON的例子(修正必要的有效性)。这个例子还演示了如何配置Jackson以允许使用单引号的JSON元素。
从原来的问题,我不明白具体问题与尝试反序列化JSON的具体问题。对于简单的数据绑定,请注意,Java属性名称必须与JSON元素名称匹配,并且Java数据结构必须与JSON数据结构匹配。
input.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
}
]
}
}
使用和不断变化的儿童,以降低情况c试过了,没有工作,为ruleAggregates代替“A”和“B” – yangdafish 2012-07-17 22:19:06
humh很奇怪,我会低级别的调试仍然得到空,我不知道为什么这不起作用(有或没有注释) – 2012-07-18 07:32:33