Search code examples
javajsonspringflurry

Can't deserialize json response from Flurry API


I am trying to read in some stats using Flurry's REST API in to my Spring application. However my objects are coming back with null values for all fields. I think this is because the JSON response prepends @ symbols to the non-array fields in the response. The responses I'm getting look like this:

{
  "@endDate": "2015-06-16",
  "@metric": "PageViews",
  "@startDate": "2015-06-16",
  "@generatedDate": "6/16/15 5:06 PM",
  "@version": "1.0",
  "day": [
          {
            "@date": "2015-06-16",
            "@value": "0"
          }
         ]
}

The code I'm using to make the request looks like this:

RestTemplate restTemplate = new RestTemplate();
FlurryAppMetric appMetric = restTemplate.getForObject(url, FlurryAppMetric.class);
return appMetric;

Where FlurryAppMetric is the following (getters & setters omitted):

public class FlurryAppMetric {
    private String metric;
    private String startDate;
    private String endDate;
    private String generatedDate;
    private String version;
    private ArrayList<FlurryMetric> day;
}

public class FlurryMetric {
    private String date;
    private String value;
}

One possible solution is to parse it all in as a map, but I'd like to take advantage of the mapper they expose if at all possible.

If there's some way to just make a GET request and receive the body as a string I would be able to clean the response and try passing it in to a mapper.


Solution

  • you should be able to parse it with GSON, using the @SerializedName annotation, like this :

    public class FlurryAppMetric {
        @SerializedName("@metric");
        private String metric;
    
        @SerializedName("@startDate");
        private String startDate;
    
        @SerializedName("@endDate");
        private String endDate;
    
        @SerializedName("@generatedDate");
        private String generatedDate;
    
        @SerializedName("@versionDate");
        private String version;
    
        @SerializedName("day");
        private ArrayList<FlurryMetric> day;
    }
    
    public class FlurryMetric {
        @SerializedName("@date");
        private String date;
    
        @SerializedName("@value");
        private String value;
    }
    

    Then use Gson like this :

        Gson gson = new Gson();
        gson.fromJson(<string json source>, FlurryApiMetric.class);