Search code examples
javajsonobjectobjectmapper

How to properly convert dto to json in Java?


How to properly convert dto to json in Java? I do it like below with using ObjectMapper:

        ObjectDto dto;
        byte[] json = new byte[0];

        dto = service.getDto(someId);

        ObjectMapper mapper = new ObjectMapper();
        json = mapper.writeValueAsBytes(dto);

and the problem is in formatting date field. In Dto i have my date in this format: 2021-09-27T12:06:27.990Z but after convert this dto to json in bytes, I see that my date is split into object with many properties like below:

"date":{
         "year":2021,
         "month":"OCTOBER",
         "nano":528000000,
         "monthValue":10,
         "dayOfMonth":25,
         "hour":13,
         "minute":14,
         "second":58,
         "dayOfYear":298,
         "dayOfWeek":"MONDAY",
         "chronology":{
            "id":"ISO",
            "calendarType":"iso8601"
         }
      },

I want to, after using ObjectMapper to have all property from Dto in this same format as before convert. How to do this?

Thanks for any help!


Solution

  • You should register a custom serializer

    public class ItemSerializer extends StdSerializer<Item> {
      ....
    }
    
    ObjectMapper mapper = new ObjectMapper();
    
    SimpleModule module = new SimpleModule();
    module.addSerializer(Item.class, new ItemSerializer());
    mapper.registerModule(module);
    

    See the full explanation here : https://www.baeldung.com/jackson-custom-serialization