Search code examples
javajsongsonjson-deserialization

JSON to Java Object deserialization


I am trying to deserialize below JSON string to Java object:

{
  "Sites": [
    "tracking.vcommission.com",
    "in.static.planet49.com",
    "feclik.com",
    "bjuyko.com",
    "facebook.com",
    "offer.alibaba.com",
    "adnetworkperformance.com",
    "click.primosearch.com",
    "yourtest-india.com",
    "amazon.in"
  ],
  "StartDate": "08/2015",
  "EndDate": "10/2015"
}

And here is the corresponding Java Object class:

public static class Output {
    private Sites[] Sites;

    public Sites[] getSites() {
       return Sites;
    }

    public void setSites(Sites[] sites) {
      this.Sites = sites;
    }
}

I am using GSON to perform the deserialization. Here is the code-

Gson gson = new GsonBuilder().create();
Output output = gson.fromJson(sitesJSONString, Output.class);

On executing, I am getting empty Sites Array. Is this because the Sites JSON Array has no keys. If so, is there any workaround to properly deserialize such a string. I googled but found nothing. Any help is appreciated.


Solution

  • Have you tried specifying the Sites to be a list of Strings?

    public static class Output {
    private List<String> Sites;
    
    public List<String> getSites() {
       return Sites;
    }
    
    public void setSites(List<String> sites) {
      this.Sites = sites;
    }
    }