以下是從原來的問題反序列化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