Jackson: How to add custom property to the JSON without modifying the POJO

后端 未结 11 1291
南方客
南方客 2020-11-27 03:10

I am developing a REST interface for my app using Jackson to serialize my POJO domain objects to JSON representation. I want to customize the serialization for some types to

11条回答
  •  庸人自扰
    2020-11-27 03:52

    I needed this ability as well; in my case, to support field expansion on REST services. I ended up developing a tiny framework to solve this problem, and it's open sourced on github. It's also available in the maven central repository.

    It takes care of all the work. Simply wrap the POJO in a MorphedResult, and then add or remove properties at will. When serialized, the MorphedResult wrapper disappears and any 'changes' appear in the serialized JSON object.

    MorphedResult result = new MorphedResult<>(pojo);
    result.addExpansionData("my_extra_field", "some data");
    

    See the github page for more details and examples. Be sure to register the libraries 'filter' with Jackson's object mapper like so:

    ObjectMapper mapper = new ObjectMapper();
    mapper.setFilters(new FilteredResultProvider());
    

提交回复
热议问题