Home > Mobile >  Convert Jackson Pojo to Different Jackson Pojo
Convert Jackson Pojo to Different Jackson Pojo

Time:01-06

I have an input that is a Jackson PoJo and I need to convert it to a different Jackson Pojo. All examples I am finding are from Json -> Pojo and Pojo -> Json. Is creating a custom serializer the way to convert from one Pojo to another?

CodePudding user response:

ModelMapper, like OneCricketeer said, or MapStruct can do the job of mapping one POJO to another POJO.

CodePudding user response:

If the field names match, or have aliases defined, you could simply serialize one object and deserialize into the other; e.g.

objectMapper.readValue(objectMapper.writeValueAsBytes(object1), Object2.class)

If the fields don't align one-to-one, there isn't a direct way

Therefore, you have some other options

  • Copy constructor / Factory method : new Object2(object1) or Object2.from(object1)
  • Builder / setter : object2.setX(object1.getX()); // repeat for all fields
  • Use a library like ModelMapper (effectively the same as options above)
  • Use reflection (very brittle and only to be used if you don't have access to modify either class)
  •  Tags:  
  • Related