Himanshu Agarwal Himanshu Agarwal - 1 year ago 71
Java Question

How to create map of java POJO class/ Json String having primitive data?

I want to make a Map (String ,Object) like this

{AssessmentId=0, Physical_name='ram', Physical_height=20, Physical_weight=60}

from my Pojo Class - InitialAssessment

public class InitialAssessment {

private long AssessmentId;

private String physical_name;

private String physical_gender;

private int physical_height;

private float physical_weight;

// all getter And setter is Created here


without using any external Library like Gson etc.

Answer Source

You can use this approach:

public Map getMapFromPojo(InitialAssessment assessment) throws Exception {

Map<String, Object> map = new HashMap<>();
if (assessment!=null ) {

Method[] methods = assessment.getClass().getMethods();

for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
Object value = "";
try {
value =  method.invoke(assessment);
map.put(name.substring(name.indexOf("get") + 3), value);
} catch (Exception e) {
return map;
return null;


It will give you map for pojo class like this:


 {AssessmentId=0, Physical_name='ram', Physical_gender='Male' , Physical_height=20, Physical_weight=60}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download