在使用Jackson进行反序列化时,重用父对象的值来构造子对象

时间:2018-02-05 15:23:20

标签: java jackson deserialization

我有两个具有冗余共享属性的类:

class Parent {
   int version;
   Child child;
}

class Child {
   int version;
   String name;
}

version中的Child字段只是Parent自己字段的本地副本,因此它在JSON中表示如下:

{
    "version": 2,
    "child": {
        "name": "john"
    }
}

我想将此JSON有效内容反序列化为具有Parent的相应parent.child.version == 2对象(该值从父项复制)。我怎样才能做到这一点?

我考虑过使用@JacksonInjectversion传递给Child,但这需要在反序列化父对象时填充注入的值。我找不到在自定义反序列化器中注册注入值的任何方法:DeserializationContext http://localhost:8500/v1/health/node/name_of_node方法只允许我们查找这样的值。

1 个答案:

答案 0 :(得分:0)

这不是特定于杰克逊的解决方案,但它可能是最简单的解决方案:创建一个{J}个类,其属性与JSON有效负载匹配,然后将df <- structure(list(id = structure(1:4, .Label = c("96", "97", "98", "99"), class = "factor"), sub = structure(c(1L, 1L, 1L, 1L), .Label = "AAA", class = "factor"), A_A1 = structure(c(1L, 4L, 2L, 3L), .Label = c("01:01:01:01/01:01:01:02N", "01:01:01:01/01:01:01:02N/01:22N", "03:01:01:01", "03:01:01:01/03:01:01:02N"), class = "factor"), A_A2 = structure(c(1L, 2L, 1L, 2L), .Label = c("29:02:01", "30:08:01"), class = "factor"), B_B1 = structure(c(1L, 2L, 1L, 2L), .Label = c("08:01:01/08:19N", "09:02:01/08:19N" ), class = "factor"), B_B2 = structure(c(1L, 1L, 1L, 1L ), .Label = "44:03:01/44:03:03/44:03:04", class = "factor"), C1 = structure(c(1L, 1L, 3L, 2L), .Label = c("07:01:01/07:01:02", "07:08:01/07:01:02", "07:09:01/07:01:02"), class = "factor")), .Names = c("id", "sub", "A_A1", "A_A2", "B_B1", "B_B2", "C_C1"), class = "data.frame", row.names = c(NA, -4L)) 转换为PreChild PreChild的构造函数。

Child