michele
michele

Reputation: 26598

Java ModelMapper Map Date to String format field

I have:

Object1.getData that returns Date objects Object2.setData that acquire a String and populate his field.

I would map a Data object from src to Object2 in the String field in yyyy-MM-dd format.

My Code:

typeMap.addMappings(mapper -> {
    ...
    mapper.map(src -> src.getData(), (dest, v) -> dest.setDataInStringFormat(formatDateToString(v)));
    ...
});

public static String formatDateToString(Object v) {
    String dateFormat = "yyyy-MM-dd";
    if(v!=null)
        return new SimpleDateFormat(dateFormat).format(v).toString();
    else return "";
}

The problem is that v is always null.

What I am doing wrong?

Thanks

Upvotes: 1

Views: 6080

Answers (1)

Andrew Nepogoda
Andrew Nepogoda

Reputation: 1895

Why don't you try to use Converter?

Converter<Date, String> formatDate = ctx -> ctx.getSource() != null
                ? formatDateToString(ctx.getSource())
                : "";
typeMap.addMappings(mapper -> mapper.using(formatDate).map(Object1::getData, Object2::setData));

Upvotes: 1

Related Questions