我正在使用 Jackson objectMapper 来解析 JSON 字符串。我将 JSON 分配给某个对象 RuleModel,其中
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模型是
RuleModel{
private long ruleId;
private Formula formula;
}
公式是
Formula{
private String ruleAggregates
private List<String> fields;
private List<FormulaModel> Children;
}
我可以获得 ruleId 值,以及第一个 ruleAggregates 的 ruleAggregates 值,但是当我尝试进入 Children 时,它得到的是公式而不是里面的值 所以当我从 child 那里得到任何值(value)时,我得到的是空值
最佳答案
以下是从原始问题中反序列化 JSON 的示例(在必要时更正以确保有效性)。此示例还演示了如何配置 Jackson 以允许单引号 JSON 元素。
从最初的问题来看,我不明白尝试反序列化 JSON 的具体问题出在哪里。对于简单的数据绑定(bind),请注意 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
}
]
}
}
关于java - Jackson objectMapping 没有获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531298/