0

My Json repose from server looks like below

{
    "duration": 0,
    "taskSummaries": [
        {
            "name": null,
            "id": 151,
            "priority": 0,
            "content": "{\"Comment\":\"Employee:{name}\",\"TaskName\":\"employeeForm\",\"GroupId\":\"HR\",\"NodeName\":\"Employee Form\"}",
            "processId": "demoProject1.busiProce1",
            "description": null,
            "subject": null,
            "statusMessage": "Ready",
            "itemID": "com.demo.tp15:demoProject1:1.0",
            "potentialOwners": [
                {
                    "name": "mary",
                    "type": "USER"
                }
            ],
            "skippable": true,
            "actualOwner": null,
            "createdBy": null,
            "createdOn": null,
            "activationTime": 1412582092211,
            "processInstanceId": 172,
            "processSessionId": 0,
            "quickTaskSummary": null,
            "parentId": null
        }
    ],
    "statusMessage": "200",
    "itemID": null,
    "processInstanceId": 172,
    "startURL": null,
    "processAppID": "demoProject1.busiProce1",
    "processAppName": null,
    "processState": {
        "description": "Active",
        "code": 1
    },
    "dueDate": null,
    "startDt": null,
    "endDt": null,
    "parentProcessInstanceId": 0,
    "outcome": null,
    "identity": null,
    "processVersion": null,
    "processName": null,
    "externalId": null
}

and i don't have control over my pojo/model object also ...as per my coding standard i have to follow naming convention for example taskSummaries will be tskSumris,name is nme,Employee is empl ..

My Question here is : I want to dynamically assign my Json string to my pojo/model when the name in json String and pojo doesnt match.

I know (in fact i have done also )if i have names are matching then i could do something like this

private Object getDynamicObject(String jsonString,Class class1) throws JsonParseException, JsonMappingException, IOException{

     ObjectMapper mapper = new ObjectMapper();
     Object dynamicObject = null;        
     dynamicObject =  mapper.readValue(jsonString,  class1); 
    return dynamicObject;
}

Can you guys please help me.

2
  • For your information my sample pojo may look like below : Commented Oct 6, 2014 at 10:45
  • @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProcessKey", propOrder = { "prcsNme", "dplyNme" }) public class ProcessKey { @XmlElement(name = "PrcsNme", required = true) protected String prcsNme; @XmlElement(name = "DplyNme", required = true) protected String dplyNme; public String getPrcsNme() { return prcsNme; } public void setPrcsNme(String value) { this.prcsNme = value; } public String getDplyNme() { return dplyNme; } public void setDplyNme(String value) { this.dplyNme = value; } } Commented Oct 6, 2014 at 10:48

2 Answers 2

1

Try out Jackson --> http://jackson.codehaus.org/ It has a bunch of libraries which helps you dynamically (de)serialize JSON and Java pojos. It is primarily done using annotations. You could yourself write some reflection based code to do the same if you don't want to ust Jackson. Locate class variables with names and types that match the JSON and similarly the reverse to create the JSON.

Ok I just noticed you mentioned you cannot control the pojo variable names. So I'd suggest using Jackson where you add annotations to the fields in the pojo. Like I said, you could create your own annotations and utility code to do the same if Jackson is not an option for you.

Edit 1: Here is a code example with Jackson, notice that the field name and the Json property name do not need to be the same.

import java.io.StringWriter;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

public class Test
{
    @JsonProperty(value="employeeName")
    private String empName;

    @JsonProperty(value="employeeAge")
    private int age;

    public static void main(String[] args) throws Exception
    {
        Test t = new Test();
        t.empName = "arun";
        t.age = 100;

        ObjectMapper m = new ObjectMapper();

        StringWriter w = new StringWriter();
        m.writeValue(w, t);
        w.close();
        String json = w.getBuffer().toString();
        System.out.println(json);

        Test t1 = m.readValue(json, Test.class);
        System.out.println(t1.empName);
        System.out.println(t1.age);
    }
}

The console output looks like this:

{"employeeName":"arun","employeeAge":100}
arun
100
Sign up to request clarification or add additional context in comments.

5 Comments

Editing the answer with a sample.
You can even next other types, i.e. if you created an Address class and had that as a field in the class above, as long as you annotate properly and keep default constructors it will all work fine.
Thanks Arun. your solution seems will work for me. let me check if i can modify my Model.
I just happen to be working on some stuff that requires the same, so a lucky connect! Glad it works!
It worked the way i wanted . But problem is i can't modify my Pojo/model.I am in discussion with technical panel here for solution.
0

Are you generating the Json directly from Pojo Model Class? What I do is something like I fetch data and then use a bean mapper to map that to a new Pojo. And each element in new mapper will have a XMLElement tag to convert to the corresponding Json/XML. Then we use a Jackson to convert that and provide it as output. So finally I have two Pojos one for Hibernate and one for mapping to Json.

2 Comments

No Akhil,we get response from third party by invoking the server.
Its painful to get assign the variable on-by-by so i am looking for dynamic solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.