Home > Enterprise >  Why do we need to convert objects into a Map?
Why do we need to convert objects into a Map?

Time:01-23

Can somebody explain (in simple words please) why we need to convert objects into a Map? I saw below code in medium.com and didn't get it:

package com.nayan.examples;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.Map;
public class ObjectToMapExample {
    public static void main(String[] args) {
        ObjectMapper oMapper = new ObjectMapper();
        Student obj = new Student();
        obj.setName("nayan");
        obj.setAge(34);
        obj.setSkills(Arrays.asList("java","angular"));
        // object -> Map
        Map<String, Object> map = oMapper.convertValue(obj, Map.class);
        System.out.println(map);
    }
}

Output:

{name=nayan, age=34, skills=[java, angular]}

Can't we just put value with key as it is without any conversion?

CodePudding user response:

The example code you found is about the concept of object mapping. The idea is: you have java objects that carry information, and you want to automatically turn that information into some other format.

Meaning: conceptually, a Student, that is just a collection of key/value pairs, like name is nayan.

The essential part here: this code shows you how to turn a Student object into another "format", in this case, a raw Map with key/value pairs.

You mainly want to use that when persistency comes into play. Meaning: say you want to store your data as JSON. Do you really want to write all the code manually that takes your objects, turns them into a JSON representation, or vice versa? No, you don't (unless for educational purposes).

  •  Tags:  
  • Related