Converting Json to java objects using Google's Gson

10,457

Since i am not having the actual api access, so i am trying it with static value in the example. Firstly in your JsonHelper class, replace all int by long , as the values mentioned in the json are of type long and String. Then try it like mentioned below:

            String str = "{\n"
            + "  \"employer\": {\n"
            + "    \"id\": 129843057436,\n"
            + "    \"name\": \"www.metroplots.com\"\n"
            + "  },\n"
            + "  \"location\": {\n"
            + "    \"id\": 102186159822587,\n"
            + "    \"name\": \"Chennai, Tamil Nadu\"\n"
            + "  },\n"
            + "  \"position\": {\n"
            + "    \"id\": 108480125843293,\n"
            + "    \"name\": \"Web Developer\"\n"
            + "  },\n"
            + "  \"start_date\": \"2012-10-01\",\n"
            + "  \"end_date\": \"2013-05-31\"\n"
            + "}";


    List<JsonHelper> json = new ArrayList<JsonHelper>();
    Gson gson = new Gson();
    JsonHelper users = gson.fromJson(str, JsonHelper.class);
    json.add(users);


    for (JsonHelper js_obj : json) {
        System.out.println(js_obj.getEmployer().getId());
        System.out.println(js_obj.getEmployer().getName());
    }
Share:
10,457
Vignesh Gopalakrishnan
Author by

Vignesh Gopalakrishnan

Fond of learning and exploring open source languages.

Updated on June 11, 2022

Comments

  • Vignesh Gopalakrishnan
    Vignesh Gopalakrishnan about 2 years

    I am using Spring Social FqlQuery to get data's from facebook. Here is the JSON response I am getting from facebook. My controller where i am getting Json output is here,

    fql = "SELECT work FROM user WHERE uid = me()";
    facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
        public Object mapObject(FqlResult result) {
            List list = (List) result.getObject("work");
            for (Object object : list) {
               JsonHelper jsonHelper = new JsonHelper();
               Gson gson = new GsonBuilder().setPrettyPrinting().create();
               String jsonOutput = gson.toJson(object);
               System.out.println(jsonOutput);
               gson.fromJson(jsonOutput, JsonHelper.class);
            }
    

    System.out.println inside for loop Outputs multiple json as below.:

    {
      "employer": {
        "id": 129843057436,
        "name": "www.metroplots.com"
      },
      "location": {
        "id": 102186159822587,
        "name": "Chennai, Tamil Nadu"
      },
      "position": {
        "id": 108480125843293,
        "name": "Web Developer"
      },
      "start_date": "2012-10-01",
      "end_date": "2013-05-31"
    }
    {
      "employer": {
        "id": 520808381292985,
        "name": "Federation of Indian Blood Donor Organizations"
      },
      "start_date": "0000-00",
      "end_date": "0000-00"
    }
    

    Here is my Helper Class:

    import java.util.List;
    
    public class JsonHelper {
    
    class Employer{
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    
    }
    class Location{
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }   
    
    }
    class Position{
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    //Edited After here
    private String start_Date;
    private String end_Date;
    private Employer employer;
    private Location location;
    private Position position;
    public String getStart_Date() {
        return start_Date;
    }
    public void setStart_Date(String start_Date) {
        this.start_Date = start_Date;
    }
    public String getEnd_Date() {
        return end_Date;
    }
    public void setEnd_Date(String end_Date) {
        this.end_Date = end_Date;
    }
    public Employer getEmployer() {
        return employer;
    }
    public void setEmployer(Employer employer) {
        this.employer = employer;
    }
    public Location getLocation() {
        return location;
    }
    public void setLocation(Location location) {
        this.location = location;
    }
    public Position getPosition() {
        return position;
    }
    public void setPosition(Position position) {
        this.position = position;
    }
    }
    

    When I try to convert the json objects to java object as done above I am getting this exception.

    HTTP Status 500 - Request processing failed; nested exception is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 6 column 16
    

    Can any one help me where I am wrong. Please help me converting json to java objects. Hope my question is clear. Thanks in advance.

    EDIT MADE TO CONTROLLER:

    facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
    public Object mapObject(FqlResult result) {
    List<JsonHelper> json = new ArrayList<JsonHelper>();
    List list = (List) result.getObject("work");
    
    for (Object object : list) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonOutput = gson.toJson(object);
        System.out.println(jsonOutput);
        JsonHelper jsonHelper = gson.fromJson(jsonOutput, JsonHelper.class);
        json.add(jsonHelper);
        System.out.println(jsonHelper.getStart_Date());
    }
    
    for (JsonHelper jsonHelper : json) {
        System.out.println(jsonHelper.getStart_Date());
    }
    
    return list;
    }
    
    });
    
  • Vignesh Gopalakrishnan
    Vignesh Gopalakrishnan over 10 years
    Thankyou for your help. I got answer. Json variable and my pojo variable should have same name. If it has same name only its getting values. Else null is printing...
  • Jhanvi
    Jhanvi over 10 years
    @VigneshGopalakrishnan Yes, in Gson, the names of variables must be same and even the dataType should be correct otherwise it creates problem.