Java introspection: object to map

后端 未结 7 966
无人及你
无人及你 2020-11-28 05:52

I have a Java object obj that has attributes obj.attr1, obj.attr2 etc. The attributes are possibly accessed through an extra level of

7条回答
  •  遥遥无期
    2020-11-28 06:23

    Here is a really easy way to do this.

    Use Jackson JSON lib to convert the object to JSON.

    Then read the JSON and convert it to a Map.

    The map will contain everything you want.

    Here is the 4 liner

    ObjectMapper om = new ObjectMapper();
    StringWriter sw = new StringWriter();
    om.writeValue(object, sw);
    Map map = om.readValue(sw.toString(), Map.class);
    

    And additional win of course is that this is recursive and will create maps of maps if it needs to

提交回复
热议问题