2

I have a entity object like this:

class Person{
 private String name;
 private String class;
 private String semester;
}

Now I have a map like this: Map<String,String>

{
   "name":"Giri"
   "class":"12"
   "semester":"C"
}

Now I want to convert this map to a Person object where each field in object corresponds to that field in map.

How can I do this?

Thanks

rudeTool
  • 526
  • 1
  • 11
  • 25

1 Answers1

6

You can write your custom mapper for this.

toPerson(Map<String, String> map) {
    if(map == null) {
        return null;
    }
    Person person = new Person();
    person.setName = map.get("name");
    person.setClass = map.get("class");
    person.setSemester = map.get("semester");
    return person;
}

Or you can use jackson convertValue()

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Person person = mapper.convertValue(map, Person.class);

Apart from jackson's ObjectMapper there are DozerBeanMapper, BeanUtils, google's Gson can be used for same purpose.

Pirate
  • 2,886
  • 4
  • 24
  • 42
  • Thanks for the detailed answer,one doubt though,what if the field that is present in person object is not available in map? is there a default value thats get set? – rudeTool Jun 19 '21 at 17:41
  • Yes default value for according to data type, int = 0, boolean = false. If you have unknown properties in the map, in that case you have to add objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); – Pirate Jun 19 '21 at 17:42
  • but if you writing your custom mapper in that case if property is not there in map, it will be assigned null values or depends on your implementation. – Pirate Jun 19 '21 at 17:45
  • yes, only if you write your custom implementation. – Pirate Jun 19 '21 at 17:46
  • This link might help you too, which is an old thread that has few approved answers... https://stackoverflow.com/questions/16428817/convert-a-mapstring-string-to-a-pojo – Aniket Jun 19 '21 at 19:00