Mapping Concatenation of Two Source Properties to One Destination Property

1,275 views
Skip to first unread message

Alex Leizerowich

unread,
May 2, 2013, 2:05:47 AM5/2/13
to model...@googlegroups.com
I have a source object with properties String A and String B.  I'd like to map A+B (concatenation) to destination object property C.  I couldn't find a way to accomplish this with a Converter.  Is it possible?

Jonathan Halterman

unread,
Jun 2, 2013, 12:05:42 AM6/2/13
to model...@googlegroups.com
Hi Alex,

Sorry for the slow response on this. The right approach would be using a Converter on the property, something like this:

Converter<String, String> c = new Converter<String, String>() {
  public String convert(MappingContext<String, String> context) {
    Src src = (Src) context.getParent().getSource();
    return src.a + src.b;
  }
};

using(c).map().setC(null);

Here we're using the Converter on a property (c) but we want to access the values of some other properties in the parent object. For this we can access the parent mapping context to get the parent source object, then concatenate the properties. I just added getParent() to the API for MappingContext to make this work.

Cheers,
Jonathan

Jonathan Halterman

unread,
Jun 7, 2013, 3:33:01 PM6/7/13
to model...@googlegroups.com
Hey Alex,

In another thread, Miha reminded me of a better solution to the problem you're working on:

using(c).map(source).setC(null);

Converter<String, String> c = new Converter<Foo, String>() {
  public String convert(MappingContext<Foo, String> context) {
    Foo foo = context.getSource();
    return foo.a + foo.b;
  }
};

This will work with the current version of ModelMapper.

Cheers,
Jonathan

On Wednesday, May 1, 2013 11:05:47 PM UTC-7, Alex L wrote:
Reply all
Reply to author
Forward
0 new messages