【发布时间】:2017-08-13 06:20:05
【问题描述】:
我正在尝试使用 gson 反序列化一些我从 SonarQube API 返回的关于各种代码指标的数据。这是从服务器返回的原始 JSON 示例:
{
"component": {
"id": "c5fc9d6k-e28b-4ea0-8922-df18c7e07ac1",
"key": "APP:master",
"name": "master",
"qualifier": "TRK",
"measures": [
{
"metric": "coverage",
"value": "19.9",
"periods": [
{
"index": 1,
"value": "0.09999999999999787"
},
{
"index": 2,
"value": "0.09999999999999787"
},
{
"index": 3,
"value": "0.6999999999999993"
},
{
"index": 4,
"value": "8.7"
}
]
},
{
"metric": "overall_coverage",
"value": "55.7",
"periods": [
{
"index": 1,
"value": "0.0"
},
{
"index": 2,
"value": "0.0"
},
{
"index": 3,
"value": "3.0"
},
{
"index": 4,
"value": "55.7"
}
]
},
{
"metric": "ncloc",
"value": "1089127",
"periods": [
{
"index": 1,
"value": "3835"
},
{
"index": 2,
"value": "3835"
},
{
"index": 3,
"value": "-74350"
},
{
"index": 4,
"value": "102501"
}
]
}
]
}
}
我正在尝试使用以下代码将其反序列化为 Component 类:
public Component getComponentMeasures(String componentKey, List<String> measures) throws ClientProtocolException,
IOException, JsonSyntaxException, UnsupportedOperationException, JSONException
{
HttpGet request = new HttpGet(baseURL + String.format("/api/measures/component?componentKey=%s&metricKeys=%s",
componentKey, StringUtils.join(measures, ",")));
HttpResponse response = client.execute(request);
Gson gson = new Gson();
String componenta = getJSONResponse(response);
System.out.print(componenta);
Component component = gson.fromJson(componenta, Component.class);
return component;
}
这是我将其反序列化为的 Component 类:
public class Component {
@SerializedName("id")
@Expose
private String id;
@SerializedName("key")
@Expose
private String key;
@SerializedName("name")
@Expose
private String name;
@SerializedName("qualifier")
@Expose
private String qualifier;
@SerializedName("path")
@Expose
private String path;
@SerializedName("measures")
@Expose
private Measure[] measures = null;
public String getId() {
return id;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getQualifier() {
return qualifier;
}
public String getPath() {
return path;
}
public Measure[] getMeasures() {
return measures;
}
}
这个组件类还包含一个Measures数组,而Measures数组又包含一个句点数组。
测量类:
public class Measure {
@SerializedName("metric")
@Expose
private String metric;
@SerializedName("value")
@Expose
private String value;
@SerializedName("periods")
@Expose
private Period[] periods = null;
public String getMetric() {
return metric;
}
public String getValue() {
return value;
}
public Period[] getPeriods() {
return periods;
}
}
期间类: 公共课期间{
@SerializedName("index")
@Expose
private Integer index;
@SerializedName("value")
@Expose
private String value;
public Integer getIndex() {
return index;
}
public String getValue() {
return value;
}
}
当我运行这段代码时,反序列化的组件为空。关于我在这里可能做错的任何事情的任何想法?请注意,组件类中有一个额外的参数“path”,它在 JSON 中为空。这是可选的并且存在于包含 Component 对象集合的其他类中。在这些情况下,这个 Component 对象和 JSON 可以很好地反序列化。我并排比较了 JSON,它们是相同的。我似乎只在尝试反序列化独立组件对象时遇到问题。任何帮助将不胜感激!
【问题讨论】: