0

I'd like to have generic transformer so any Java object is transformed into a Map and nested objects are represented as nested Maps. E.g.

class MyA {
  String a;
  Integer b;
  MyB c;
  List<MyD> d;
}
class MyB {
  Double a;
  String b;
  MyB c;
}
class MyD {
  Double a;
  String b;
}

transformed into:

Map {
  a:anyValue
  b:5
  c:Map {
    c:Map {
      a:asdfValue
      b:5.123    
      c:Map {
        a:fdaValue
        b:3.123
        c:null
      }
    }
  }
  d:Map {
    1:Map {
      a:aValue
      b:5.5
    }
    2:Map {
      a:bValue
      b:5.6
    }
  }
}

Please post your solutions for any transformation framework.

1 Answers1

1

You could actually easily implement this yourself:

public Map<String, Object> convertObjectToMap(Object o) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    for (Field f : o.getClass().getDeclaredFields()) {
        f.setAccessible(true);
        Object value = f.get(o);
        if ((value instanceof Integer) || (value instanceof String) /* other primitives... */)
            map.put(f.getName(), value);
        else if (value instanceof Collection<?>) {
            int listindex = 0;
            for (Object listitem : (Collection<?>)value)
                map.put(f.getName() + "_" + listindex++, listitem);
        }
        else
            map.put(f.getName(), convertObjectToMap(value));
    }
    return map;
}
main--
  • 3,873
  • 1
  • 16
  • 37
  • Thanks main, good answer for the question, but this is not the only bit I need to do here. Some fields will be mapped strictly and this part may vary for diff object graphs. So I hope there will be some examples with transformation frameworks. – Ivan Velykorodnyy Sep 05 '12 at 21:51