Object mapping fields

1.4k views Asked by At

I have an objects class A:

  public class A {
    private Long id;
    private String name;
    private String mail;
    private String moreData;
    // ...
  }

class B:

  public class B {
    private Long id;
    private String name;
    private String crc;
    // ...
  }

Can I use jackson to provide field mapping from object A to B copying correspond fields into target object.

I need from object

  A {
    Long id = 23L;
    String name = "name";
    String mail = "mail";
    String moreData = "moreData";
    // ...
  }

get as target object

  B {
    Long id = 23L;
    String name = "name";
    String crc = mull;
    // ...
  }

after object mapping processing...

Is it possible implement solution using com.fasterxml.jackson in simple way?

1

There are 1 answers

0
Andrew Phillips On BEST ANSWER

Sure you can. Not withstanding a full understanding of why you want to do this, or that I think there might be more efficient ways than converting to JSON then back, but if you would like to use Jackson, here is what I would do:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
B b = objectMapper.readValue(objectMapper.writeValueAsString(a), B.class);

Hope this helps. should do the job. The key will be to tell Jackson to not fail on unknown properties so it drops those you are not sure of.