A Bean object in the form of a POJO containing a set of property definitions and corresponding GET and set methods. So we need to use Java’s reflection method getDeclaredFields() to get the list of fields in this object. Because properties are generally defined as private, you must use the getDeclaredFields() method, which gets all declaration fields of a class, including public, private, and proteced, but not declaration field 1 of the parent class. Here is the implementation code:

private Map<String, Object> toMap(Object obj) { Map<String, Object> result = new HashMap<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String key = field.getName(); Object value; try { value = field.get(obj); } catch (Exception e) {log.warn(" Cannot fetch object named "+ field.getName() +", set it to null. , e); continue; } result.put(key, value); } return result; }Copy the code

Because the property is private, you must use the setAccessible(true) method to make it accessible.

The previous code is not practical because properties of type Date are resolved as timestamps.

We can use the Jackson component, which defines the format of properties of type Date. Like:

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

 private Date areaTime;
Copy the code

Jackson’s JSON object ObjectMapper can be converted into a Map object:

Map<String, Object> values =

 objectMapper.readValue(objectMapper.writeValueAsString(paramValues),

 Map.class);
Copy the code

Here, the Bean object is converted to a string and then to a Map object. ObjectMapper reads the @JsonFormat annotation in the Bean property and transforms it according to the defined format.


[1] The difference between getFields() and getDeclaredFields () in JAVA reflection