Jackson,使用私有字段和没有注释的 arg-constructor 反序列化类

新手上路,请多包涵

可以反序列化为具有私有字段和自定义参数构造函数的类,而无需使用注释且无需修改类,使用 Jackson?

我知道在 Jackson 中使用这种组合是可能的:1) Java 8,2) 使用“-parameters”选项编译,以及 3) 参数名称与 JSON 匹配。但是默认情况下在 GSON 中也可以没有所有这些限制。

例如:

 public class Person {
    private final String firstName;
    private final String lastName;
    private final int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public static void main(String[] args) throws IOException {
        String json = "{firstName: \"Foo\", lastName: \"Bar\", age: 30}";

        System.out.println("GSON: " + deserializeGson(json)); // works fine
        System.out.println("Jackson: " + deserializeJackson(json)); // error
    }

    public static Person deserializeJackson(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        return mapper.readValue(json, Person.class);
    }

    public static Person deserializeGson(String json) {
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(json, Person.class);
    }
}

这适用于 GSON,但 Jackson 抛出:

 Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `jacksonParametersTest.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{firstName: "Foo", lastName: "Bar", age: 30}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)

这在 GSON 中是可能的,所以我希望 Jackson 中一定有某种方法无需修改 Person 类,无需 Java 8,也无需显式自定义反序列化器。有人知道解决方案吗?

  • 更新,附加信息

Gson 似乎跳过了参数构造函数,因此它必须使用反射在幕后创建一个无参数构造函数。

此外,存在一个 Kotlin Jackson 模块,即使没有“-parameters”编译器标志,它也能够为 Kotlin 数据类执行此操作。所以奇怪的是,Java Jackson 似乎不存在这样的解决方案。

这是 Kotlin Jackson 中可用的(干净整洁的)解决方案(IMO 也应该通过自定义模块在 Java Jackson 中可用):

 val mapper = ObjectMapper()
    .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
    .registerModule(KotlinModule())

val person: Person = mapper.readValue(json, Person::class.java)

原文由 Devabc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 735
1 个回答

带有混合注解的解决方案

您可以使用 _混合注释_。当修改类不是一个选项时,这是一个很好的选择。您可以将其视为一种在运行时添加更多注释的面向方面的方式,以扩充静态定义的注释。

假设您的 Person 类定义如下:

 public class Person {

    private final String firstName;
    private final String lastName;
    private final int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    // Getters omitted
}

首先定义一个mix-in注解抽象类:

 public abstract class PersonMixIn {

    PersonMixIn(@JsonProperty("firstName") String firstName,
                @JsonProperty("lastName") String lastName,
                @JsonProperty("age") int age) {
    }
}

然后配置 ObjectMapper 使用定义的类作为 POJO 的混合:

 ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
mapper.addMixIn(Person.class, PersonMixIn.class);

并反序列化 JSON:

 String json = "{firstName: \"Foo\", lastName: \"Bar\", age: 30}";
Person person = mapper.readValue(json, Person.class);

原文由 cassiomolin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题