Wednesday, November 20, 2013

JSON Array to Java List objects

https://github.com/FasterXML/jackson

In one of my project, I had to map the JSON string to Java objects. Mapping a simple POJO was not a problem. Mapping a list of String also not a problem. But I had to map a list of Java object.

I had to spend many hours of searching; couldn't find a simple answer.

Then, finally I found out; it was a simple add method. I had to add the Java object into that list.
Here is the list of various components:

incoming JSON:

 {
   "title": "software developer",
   "description": "good developer at some company",
   "keywords":["java", "soa", "bigdata"],
   "educationList":  [{
                              "course": "Bachelor of Science",
                               "institution":  "Madras University",
                               "startYear": "1979",
                                "endYear": "1982"
                          } ,

                          {
                              "course": "Master of Science",
                               "institution":  "Stanford University",
                               "startYear": "1989",
                               "endYear": "1993"
                          }
                    ]
 
}

POJO:

public class SeedProfile {
    private String title;
    private String description;
    private List<String> keywords;
    private List<EducationObject> educationList = new ArrayList<EducationObject>();
   
    public List<EducationObject> getEducationList() {
        return educationList;
    }

    public void setEducationList(List<EducationObject> educationList) {
        this.educationList = educationList;
    }
   
    public void addEducationObject(EducationObject educationObject){
        educationList.add(educationObject);
    }
}

servlet processing request:

            ObjectMapper mapper = new ObjectMapper();
            String incomejson = req.getParameter("incomejson");
            System.out.println(incomejson);
            SeedProfile seed = mapper.readValue(incomejson, SeedProfile.class);
          
 servlet response:

            out.println(seed.getTitle());out.println("<br/>");
            out.println(seed.getKeywords());out.println("<br/>");
            List list = seed.getEducationList();
            ListIterator it = list.listIterator();
            while(it.hasNext()){
                EducationObject edu = (EducationObject) it.next();
                out.println(edu.getInstitution());out.println("<br/>");
            }