我的代码工作正常。我很想知道这个特定用例的方法是否好,因为我找不到改进的例子不使用GSON或其他JSON解析库但只是使用POJO来保存数据。
(注意,我一直在尝试格式化我的代码!对此抱歉)
对于此示例,我从TMDB的API请求数据:.../3/movie/{id}?API_KEY=x
以JSON格式返回的数据(已减少。请关注“评论”对象)
{
"vote_count":2034,
"reviews":{
"page":1,
"results":[
{
"id":"55660928c3a3687ad7001db1",
"author":"Phileas Fogg",
"content":"Fabulous action movie. Lots of interesting characters. They don't make many movies like this. The whole movie from start to finish was entertaining I'm looking forward to seeing it again. I definitely recommend seeing it.",
"url":"http://j.mp/1HLTNzT"
},
{
"id":"55732a53925141456e000639",
"author":"Andres Gomez",
"content":"Good action movie with a decent script for the genre. The photography is really good too but, in the end, it is quite repeating itself from beginning to end and the stormy OST is exhausting.",
"url":"http://j.mp/1dUnvpG"
}
],
"total_pages":1,
"total_results":2
},
"trailers":{
"quicktime":[
],
"youtube":[
{
"name":"Trailers From Hell",
"size":"HD",
"source":"FRDdRto_3SA",
"type":"Featurette"
},
{
"name":"Trailer 2",
"size":"HD",
"source":"jnsgdqppAYA",
"type":"Trailer"
},
{
"name":"Official Trailer #1",
"size":"HD",
"source":"YWNWi-ZWL3c",
"type":"Trailer"
}
]
}
创建了Retrofit Interface。希望我能在这里展示,但格式是精神上的。
这是一个奇怪的部分。我创建了一个POJO,如下所示,它工作正常。
public class TMDBMovieDetailsRetrofitObj {
//在movie / id端点中可用的运行时 public String runtime;
public String tagline;
公众评论评论;
公共课程评论{
public Reviews() { reviews = new Reviews(); }
// To know how many reviews we have got!
public String total_results;
public List<ReviewResults> results;
public class ReviewResults{
public ReviewResults() {
results = new ArrayList<>();
}
public String id;
public String author;
public String content;
public String url;
}
} }
没有创建getter和setter方法,因为我有另一个包含大量信息的TMDBMovie对象,并且拥有自己的getter和setter方法。
你认为这两点是否正常:
这个POJO有3个级别的公共嵌套类,Retrofit处理得非常好。
我有一个TMDBMovie对象,它有自己的getter和setter方法,通过它我可以进行检查,验证和次要数据操作。如果公共变量正常,这个POJO是否需要getter和setter方法?
答案 0 :(得分:1)
命名您的类变量,以便将JSON转换为Java对象是一个好主意。但是,这些类不需要嵌套。您可以定义List<Result> results
并在其他位置定义Result类。希望这很清楚。
答案 1 :(得分:1)
TMDBMovieDetailsRetrofitObj.java
public class TMDBMovieDetailsRetrofitObj {
// Runtime available in movie/id endpoint
public String runtime;
public String tagline;
public Reviews reviews;
}
Review.java
public class Reviews {
// To know how many reviews we have got!
public String total_results;
public List<ReviewResults> results;
}
ReviewResults.java
public class ReviewResults {
public String id;
public String author;
public String content;
public String url;
}