9

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.

  • 6
    what is `obj`, what is `parameter`, ... what is the input, what is the expected output? – luk2302 Sep 19 '18 at 13:01
  • You'll want to use Java reflection. [This](https://stackoverflow.com/questions/16171637/java-reflection-how-to-get-field-value-from-an-object-not-knowing-its-class#16172206) may help you. – hyper-neutrino Sep 19 '18 at 13:08
  • for exaple: `Object obj = new myObject("Joe", "Doe");` convert to `Map` with keys: name, surname and values Joe, Doe – Dmytro Svarychevskyi Sep 19 '18 at 13:12
  • 2
    Why do you want to do this? This has potential to raise many issues especially relating to scoping (only public variables can be fetched, not even default ones). Is there something you're looking to do with this? There is likely a better solution. – hyper-neutrino Sep 19 '18 at 13:19

2 Answers2

21

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}
Hearen
  • 6,951
  • 2
  • 47
  • 57
8

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.

hyper-neutrino
  • 5,007
  • 2
  • 25
  • 47