Immutable/polymorphic POJO <-> JSON serialization with Jackson

后端 未结 3 1840
南方客
南方客 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:30

    Have a look at Genson library some of its key features are adressing your exact problem: polymorphism, not requiring annotations and most important immutable pojos. Everything works in your example with 0 annotations or heavy conf.

    Genson genson = new Genson.Builder().setWithClassMetadata(true)
                                .setWithDebugInfoPropertyNameResolver(true)
                                .create();
    
    String jsonCircle = genson.serialize(circle);
    String jsonRectangle = genson.serialize(rectangle);
    
    System.out.println(jsonCircle); // {"@class":"your.package.Circle","radius":123}
    System.out.println(jsonRectangle); // {"@class":"your.package.Rectangle","w":20,"h":30}
    
    // Throws nothing :)
    Shape newCircle = genson.deserialize(jsonCircle, Shape.class);
    Shape newRectangle = genson.deserialize(jsonRectangle, Shape.class);
    

    Genson gives you also the ability to use aliases (used instead classes names).

    new Genson.Builder().addAlias("shape", Shape.class)
                    .addAlias("circle", Circle.class)
                    .create();
    

提交回复
热议问题