lundi 20 mai 2019

Object in Object to HashMap with reflection

Project:

I am currently using a tool called Netuno to develop an api, so to do the export of objects to json it is necessary to do the transformation of the object to HashMap, for this a method was developed in a parent class to export the object.

The method:
   public Map<String, Object> export() {
        Object obj = this;
        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) {
                //todo e
            }
        }
        return map;
    }

This works, but only for simple objects.

My problem:

If the object has complex objects inside my method it has no ability to export them to HashMap either.

Example structure:

public abstract class Master {
 public Map < String, Object >
  export () {
   Object obj = this;
   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) {
     //todo e
    }
   }
   return map;
  }
}

public class Foo extends Master {
 private int a;
 private int b;
 private String c;
 private Bar bar;
//...
}

public class Bar extends Master {
 private int q;
 private int w;
 private String e;
//...
}


I use it this way:

return new Bar(/*data*/).export();

Output:

{
  "a": 2,
  "b": 5,
  "c": "abc",
  "bar": "myproject.myPackage.Bar@XXXXX"
}

Expected Output:

{
  "a": 2,
  "b": 5,
  "c": "abc",
  "bar": {
    "q": 10,
    "w": 15,
    "e": "it works"
  }
}





Aucun commentaire:

Enregistrer un commentaire