我正在尝试解析the Json result returned from this url。我想获得标题,内容和缩略图值。我试图创建一个java类来映射这些值。
import java.util.List;
public class Dbpediaresults {
private Results results;
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
public static class Results {
private List<Bindings> bindings;
public List<Bindings> getBindings() {
return bindings;
}
public void setBindings(List<Bindings> bindings) {
this.bindings = bindings;
}
}
public static class Bindings {
private List<Title> title;
private List<content> content;
private List<Thumbnail> thumbnail;
/**
* @return the title
*/
public List<Title> getTitle() {
return title;
}
public void setTitle(List<Title> title) {
this.title = title;
}
public List<content> getContent() {
return content;
}
public void setContent(List<content> content) {
this.content = content;
}
public List<Thumbnail> getThumbnail() {
return thumbnail;
}
public void setThumbnail(List<Thumbnail> thumbnail) {
this.thumbnail = thumbnail;
}
}
private static class Title {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private static class content {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private static class Thumbnail {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
我试过这个以获得结果,但它没有工作。
Dbpediaresults results = new Gson().fromJson(input, Dbpediaresults.class);
此处输入是从上面的URL返回的json输出的String
。
我的Dbpediaresults
类是否正确映射标题,内容和缩略图值?如果没有,我该如何正确解析它?
答案 0 :(得分:1)
Gson不会将List<Binding>
组分成三个单独的列表。解决此问题的最简单方法是创建包含单个Binding
,其中List
是一个代表所有三个标题,内容和缩略图的类。最好将这些保持在一起,因为多个并行class Content
是strong hint that there's a class waiting to be born.
这是一些示例代码。除了解决问题之外,我还进行了一些其他次要样式和变量名称更改(例如public class Dbpediaresults {
private Results results;
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
public static class Results {
private List<Binding> bindings;
public List<Binding> getBindings() {
return bindings;
}
}
public static class Binding {
private Title title;
private Content content;
private Thumbnail thumbnail;
public Title getTitle() {
return title;
}
public Content getContent() {
return content;
}
public Thumbnail getThumbnail() {
return thumbnail;
}
}
public static class Title {
private String value;
public String getValue() {
return value;
}
}
public static class Content {
private String value;
public String getValue() {
return value;
}
}
public static class Thumbnail {
private String value;
public String getValue() {
return value;
}
}
}
在代码中为小写,并删除了setter。)
{{1}}