简体   繁体   中英

Copying variables from one POJO to another

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 ?

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>(){});

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/

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM