16

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

30

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
  • 7,420
  • 4
  • 53
  • 63
  • 3
    Where is `MapHelper` defined/provided from? – fragmentedreality Jul 23 '20 at 07:29
  • 1
    @fragmentedreality Untested but I think something this will work: https://gist.github.com/qb20nh/5354dba41827cad3e72caeaf50659b9b – Monday Fatigue Oct 04 '21 at 10:10
  • @MondayFatigue a simple Map.class will work too – Joand Jan 24 '22 at 16:32
  • When I do this it converts everything in the hashmap to a string – Collin Feb 18 '22 at 17:02
  • 1
    If you need a typed map, this worked for me: Map objMap = objectMapper.convertValue(obj,TypeFactory.defaultInstance().constructMapType(HashMap.class,String.class,Object.class)); – Shy Albatross Mar 25 '22 at 21:47
  • The only disadvantage to this can be that this does a deep conversion, so if there are objects inside the object, it will create a map inside your map (or fail the conversion if it doesn't know how to convert the object). Maybe this is what you want, but in some cases you want a shallow conversion, so in that case this solution doesn't work. You'd want @hyper-neutrino 's solution in that case. – Rik Schaaf Oct 27 '22 at 16:31
  • More generic approach: MAPPER.convertValue(structure, new TypeReference>() {}) – Leonis Dec 16 '22 at 21:27
12

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,272
  • 2
  • 29
  • 50