This is a common mistakes done by jquery developers. Say you have a form (with form tags) and you extract the form data and create a json object and send it to a url via ajax. Also lets say your action is also the ajax url. Then if you send the content via jquery ajax, pre-request callback will append the form content to the jason object you extracted. So in order to avoid this you can set return to false in the form.
Showing posts with label json. Show all posts
Showing posts with label json. Show all posts
Tuesday, November 27, 2012
Tuesday, November 20, 2012
Jackson access node elements and binding sub trees in to java objects
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);
Subscribe to:
Posts (Atom)