Convert object to map in java

Viewed 47475

how I can convert Object to Map<String, String> where key is obj.parameter.name and value is obj.parameter.value

for exaple: Object obj = new myObject("Joe", "Doe"); convert to Map with keys: name, surname and values: Joe, Doe.

2 Answers

Apart from the trick solution using reflection, you could also try jackson with one line as follows:

objectMapper.convertValue(o, Map.class);

A test case:

    @Test
    public void testConversion() {
        User user = new User();
        System.out.println(MapHelper.convertObject(user));
    }

    @Data
    static class User {
        String name = "Jack";
        boolean male = true;
    }


// output: you can have the right type normally
// {name=Jack, male=true}

This is how you'd do it:

import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import java.lang.reflect.Field;

public class Main {
    public int a = 3;
    public String b = "Hello";

    public static void main(String[] args) {
        Map<String, Object> map = parameters(new Main());
        for (Entry<String, Object> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

    public static Map<String, Object> parameters(Object obj) {
        Map<String, Object> map = new HashMap<>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try { map.put(field.getName(), field.get(obj)); } catch (Exception e) { }
        }
        return map;
    }
}

Basically, you use reflection to get all of the fields in the class. Then, you access all of those fields of the object. Keep in mind that this only works for fields accessible from the method that gets the fields.

Related