0

I have following usecase:

I'm having map with properties:

Map <String, String[]> args = new HashMap(){{
put("requester.firstName", "Alice");
put("requester.lastName", "Smith");
put("requester.address", "Glasgow Av");
put("publication.type", "print");
put("publication.subtype", "book");
}};

I need to convert it to this pojo

public class WebRequest{
private Requester requester;
private Publication publication;
}

class Requester{
private String firstName;
private String lastName;
private String address;
}

class Publication{
private String type;
private String subType;
}

Can I use Jackson, to run the conversion? If not, what is the best suitable library for this?

Thanks,

Nadiia

Nadja
  • 19
  • 4

2 Answers2

0

You might be able to use the BeanUtils of apache common. That framework is capable to map from a Map to a bean almost instantly.

Map<String,String> yourMap = new HashMap<String,String>();
yourMap.put("name", "Joan");
yourMap.put("age", "30");

YourBean p = new YourBean();

try {
    BeanUtils.populate(p, yourMap);
}  catch (Throwable e) {
    //do something...
}

What I'm not sure about is whether it automatically recognizes nested objects and corresponding properties but maybe you are able to do this di-visioning manually (by offering 2 maps, etc).

More information can be found here BeanUtils

uniknow
  • 938
  • 6
  • 5
0

I found here on StackOverflow excellent solution for my problem. Similar problem,
BeanUtils converting java.util.Map to nested bean

One of the answers was perfect:

You should use Spring's BeanWrapper class. It supports nested properties, and optionally create inner beans for you:

BeanOne one = new BeanOne();
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(one);
wrapper.setAutoGrowNestedPaths(true);

Map<String, Object> map = new HashMap<>();
map.put("fieldOne", "fieldOneValue");
map.put("fieldTwo.fieldOne", "fieldOneValue");

wrapper.setPropertyValues(map);

assertEquals("fieldOneValue", one.getFieldOne());
BeanTwo two = one.getFieldTwo();
assertNotNull(two);
assertEquals("fieldOneValue", two.getFieldOne();

I hope it will help somebody with similar problem.

Community
  • 1
  • 1
Nadja
  • 19
  • 4