我有一个看起来像这样的JSON对象:
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"codexperiments"
},
"Web":{
"Total":41,
"Offset":0,
"Results":[
{
"Title":"Code Xperiments - Because IT is an experimental science",
"Description":"The deferred-time page scrolling technique I described in my previous article is not what I really wanted to achieve at first. Although powerful, it lacks of “dynamism”.",
"Url":"http:\/\/www.codexperiments.com\/",
"CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=codexperiments&d=4548825798150827&mkt=en-US&w=a8960869,c9182d07",
"DisplayUrl":"www.codexperiments.com",
"DateTime":"2011-01-14T16:19:00Z"
}
]
}
}
}
我正在尝试使用gson解析标题/ url
public class GoogleResults {
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Results[url:" + url +",title:" + title + "]"; }
}
}
和
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
但我的结果始终为空。有什么想法我错过了吗?
答案 0 :(得分:3)
确保将数据结构与JSON数据结构匹配,否则将无法正确解析。另外,就像另一个回答的人所说的那样,在JSON中命名他们的名字。同样,如果变量在JSON中大写,请记住将变量大写。
public class Result {
SR SearchResponse;
static class SR {
W Web;
static class W {
List<R> Results;
static class R {
public String Url;
public String Title;
public String toString() {
return Url + Title;
}
}
}
}
public String toString() {
return SearchResponse.Web.Results.toString();
}
}