杰克逊 - 自定义反序列化程序不会读取 JSON 中的所有字段



>我从API收到这个JSON:

"link": [],
"firstRecord": 1,
"item": [
{
"Customer": {
"id": "1058207",
"firstName": "foo",
"lastName": "foo2",
"nestedObj1": {
"id": "40008"
},
"nestedObj2": {
"link": [],
"linkfoo": "lala",
"item": [
{
"id": "266614",
"label": "NESTED_OBJ_2"
}
]
}
]
}

我的反序列化程序函数

@Override
public CustomerView deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
//tried this too
TreeNode treeNode = p.getCodec().readTree(p);
// also this
JsonNode node = p.getCodec().readTree(p);
JsonNode simpleNode = new ObjectMapper().readTree(p);
// use for each field that is not String
ObjectMapper mapper = new ObjectMapper();
Customer customer = new Customer();
customer.setFirstName(simpleNode.get("Customer").get("firstName").textValue()); 
NestedObj2[] arrayObj2 = mapper.readValue(
simpleNode.get("Customer").get("nestedObj2").get("item").toString(), 
NestedObj2[].class);
customer.setArrayObj2(arrayObj2);
}

类 NestedObj2 具有 JSON 中的所有字段,"item"数组是单独的对象作为字段。

问题是,JsonNode和TreeNode都没有看到字段"nestedObj2",但是其余字段在反序列化时位于其中 ->调试时检查

。 我是否在配置中遗漏了某些内容,或者我应该使用其他对象进行反序列化?

谢谢!

编辑

最后,我按照HosseinNejad的建议使用了DTO@Mehrdad。 由于我通过RestTemplate.exchange()接收此 JSON,我必须使用像这里这样的MappingJacksonHttpMessageConverter配置RestTemplatehttps://stackoverflow.com/a/9381832/12677470

使用 DTO 类可能是一个更好的主意,无需创建自定义反序列化程序

我编写了一个示例嵌套 DTO,如下所示

为客户创建 DTO 类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
private Long id;
private String firstName;
private String lastName;
private NestedObj1 nestedObj1;
private NestedObj2 nestedObj2;
//getter and setter
}

为 NestedObj1 创建 DTO 类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class NestedObj1 {
private Long id;
//getter and setter
}

为 NestedObj2 创建 DTO 类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class NestedObj2 {
private List<String> link;
private String linkFoo;
private List<Item> item;
//getter and setter     
}

为项目创建 DTO 类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Item {
private Long id;
private String label;
//getter and setter
}

创建这些 DTO 后,您可以简单地使用 ObjectMapper 类 将 JSON 转换为 Java 对象

Customer customer= new ObjectMapper().readValue(jsonFile, Customer.class);

有关更多选项,例如忽略某些属性,...您可以使用以下链接:

杰克逊注释示例

反序列化中的详细信息:

杰克逊反序列化入门

最新更新