简体   繁体   中英

JSON dynamic deserialization in java

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM