Immutable/polymorphic POJO <-> JSON serialization with Jackson

后端 未结 3 1839
南方客
南方客 2021-02-08 06:00

I\'m trying to serialize a immutable POJO to and from JSON, using Jackson 2.1.4, without having to write a custom serializer and with as few annotations as possible. I also like

3条回答
  •  后悔当初
    2021-02-08 06:42

    Rectangle has two parameters, and the FAQ says:

    Deserializing simple types

    If I want to deserialize simple JSON values (Strings, integer / decimal numbers) into types other than supported by default, do I need to write a custom deserializer?

    Not necessarily. If the class to deserialize into has one of:

    • Single-argument constructor with matching type (String, int/double), or
    • Single-argument static method with name "valueOf()", and matching argument type

    Jackson will use such method, passing in matching JSON value as argument.

    I'm afraid you have to write your own deserializer as show in the Jackson documentation:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule testModule =
       new SimpleModule("MyModule", new Version(1, 0, 0, null))
          .addDeserializer( MyType.class, new MyTypeDeserializer());
    mapper.registerModule( testModule );
    

提交回复
热议问题