Home > Software design >  How to get value from java object?
How to get value from java object?

Time:11-15

public boolean mediate(MessageContext synCtx) {
    Object obj = synCtx.getProperty("RequestPayload");       
    System.out.println(obj);        
    return true;
}

From above code I can see output like below.

{
    "name" : "Jone",
    "marks" : "45"
}

Can I know how I print name from that object. I tried like below but its not working.

System.out.println(obj.get("name").toString());

Can anyone help me I am new to this.

CodePudding user response:

It seems like obj is a JSON string. You will need to use a library like GSON (https://github.com/google/gson) to parse it, either to another object or to a map.

Examples for map:

class Main {
    private Gson gson = new Gson();
    public boolean mediate(MessageContext synCtx) {
        String obj = synCtx.getProperty("RequestPayload").toString();       
        Map<String, Object> result = gson.fromJson(obj, Map.class);
        System.out.println(result.get("name"));        
        return true;
    }
}
  • Related