3

I have one POJO 'A' and it has more than 30 variables. I have another POJO 'B' and most of the variables are same as in 'A'.

For example A has one variable var1 as List of LocalDate and B has a attribute with the same name var1 but as List of Long (long value of date). Now from the REST Service I got the response in 'B' and my old customers are still using 'A'. I want to convert the response from B to A. As my all other values are same except variable var1, what would be most efficient way to copy all other attributes from var2 to var1? Is there any library that provides such method ?

Ankur Chaudhari
  • 111
  • 3
  • 7
  • Is one POJO a subset of the other? or do they have common subsets? – Scary Wombat Apr 16 '19 at 05:26
  • 3
    It would be better to represent your question as a sample class code than describing it. – Samuel Robert Apr 16 '19 at 05:29
  • A's properties are subset of B's? If that's the case, https://stackoverflow.com/questions/5455014/ignoring-new-fields-on-json-objects-using-jackson gives you answer (if you can change A's code at least in your project). – Edward Aung Apr 16 '19 at 05:54

3 Answers3

2

The best way is to write a mapper method that maps the object of A to object of B. This is the safest and recommended way of doing it.

If you are okay to dirty your code.. you can serialize the objA and then deserialize it to objB. Make sure all the non-nullable fields are available in both the objects and be ready to catch parsing exceptions. In fact, the names of the fields should also be the same in both classes unless mapped to different names(aliases) (ex. with some kind of Jackson annotations). If the names of the fields are not the exact same they will be dropped.

B objB = Json.deserialize(JSON.serialize(objA), new TypeReference<B>(){});
raviiii1
  • 936
  • 8
  • 24
1

You could be done using Gson

Gson gson = new Gson();
Type type = new TypeToken<YourPOJOClass>(){}.getType();
String data = gson.toJson(workingPOJO);
coppiedPOJO = gson.fromJson(data, type);
Arup
  • 131
  • 5
0

You can use a mapping library like dozer to map two classes with same fields. You can exclude the fields which are different in both the POJOs and map them yourself.

Refer this link for more details http://dozer.sourceforge.net/

Gaurav Sahu
  • 23
  • 1
  • 3