我试图在我的Spring应用程序中使用Flurry的REST API读取一些统计信息。但是,我的对象返回的所有字段均为空值。我认为这是因为JSON响应会将@符号添加到响应中的非数组字段。我得到的响应如下所示:
{
"@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"
}
]
}
我用来发出请求的代码如下所示:
RestTemplate restTemplate = new RestTemplate();
FlurryAppMetric appMetric = restTemplate.getForObject(url, FlurryAppMetric.class);
return appMetric;
其中FlurryAppMetric是以下内容(省略了getter和setter):
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;
}
一种可能的解决方案是将其全部解析为地图,但我想尽可能利用它们公开的映射器。
如果有某种方法可以发出GET请求并以字符串形式接收主体,则可以清除响应并将其传递给映射器。
您应该能够使用@SerializedName
注释使用GSON对其进行解析,如下所示:
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;
}
然后像这样使用Gson:
Gson gson = new Gson();
gson.fromJson(<string json source>, FlurryApiMetric.class);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句