Say you have several types of pojos and you need to send them in json format. Finally you need to deserialize them. In this post lets see how you can access subtrees of the json object and deserialize them in to pojos.
In this example we are using jackson. Another popular json serialize/deserialize library is google's gson library. How ever the gson library does not support maps at the moment. Therefore you cannot use key/value concept to access the json object.
Now let's see how we can do this. In this example, the json string contains lecturer object and an array of subject ids. Say we need to get these two objects separately.
ObjectMapper mapper = new ObjectMapper();//need this to deserialize in to required pojo
JsonNode rootNode = mapper.readTree(json);//json is the json string.
JsonNode lecturerNode = rootNode.path("lecturer");//get the lecturer node from json root node using the related key.
JsonNode subjectIdNode = rootNode.path("selectedSubjects");//get the array from json root node using the related key.
Lecturer lecturer = mapper.readValue(lecturerNode, Lecturer.class);//use the mapper to get the object
String[] subjectIdList = mapper.readValue(subjectIdNode, String[].class);
In this example we are using jackson. Another popular json serialize/deserialize library is google's gson library. How ever the gson library does not support maps at the moment. Therefore you cannot use key/value concept to access the json object.
Now let's see how we can do this. In this example, the json string contains lecturer object and an array of subject ids. Say we need to get these two objects separately.
ObjectMapper mapper = new ObjectMapper();//need this to deserialize in to required pojo
JsonNode rootNode = mapper.readTree(json);//json is the json string.
JsonNode lecturerNode = rootNode.path("lecturer");//get the lecturer node from json root node using the related key.
JsonNode subjectIdNode = rootNode.path("selectedSubjects");//get the array from json root node using the related key.
Lecturer lecturer = mapper.readValue(lecturerNode, Lecturer.class);//use the mapper to get the object
String[] subjectIdList = mapper.readValue(subjectIdNode, String[].class);
No comments:
Post a Comment