所以,这是您返回的 JSON。
{
"batchcomplete": "",
"query": {
"normalized": [{
"from": "pizza",
"to": "Pizza"
}],
"pages": {
"24768": {
"pageid": 24768,
"ns": 0,
"title": "Pizza",
"extract": "Pizza is a yeasted flatbread generally topped with tomato sauce and cheese and baked in an oven. It is commonly topped with a selection of meats, vegetables and condiments. The term was first recorded in the 10th century, in a Latin manuscript from Gaeta in Central Italy. The modern pizza was invented in Naples, Italy, and the dish and its variants have since become popular and common in many areas of the world.\nIn 2009, upon Italy's request, Neapolitan pizza was safeguarded in the European Union as a Traditional Speciality Guaranteed dish. The Associazione Verace Pizza Napoletana (the True Neapolitan Pizza Association) is a non-profit organization founded in 1984 with headquarters in Naples. It promotes and protects the \"true Neapolitan pizza\".\nPizza is sold fresh or frozen, either whole or in portions, and is a common fast food item in Europe and North America. Various types of ovens are used to cook them and many varieties exist. Several similar dishes are prepared from ingredients commonly used in pizza preparation, such as calzone and stromboli."
}
}
}
}
这是您的(精简的)Java 类。
public class WikiInfo {
private String name;
private String extract;
}
Retrofit 将 JSON 处理委托给您在此处设置的 Gson。
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
试图从 JSON 中知道你想要什么时遇到问题,它不能简单地知道你想要 response["query"]["pages"],然后是页面 ID #24768,以及 "title" 和 "extract"。
所以,解决办法是要么
- 不要重新发明轮子。为 Wikipedia 查找合理的 Java API 或查看现有的 Retrofit Wikipedia 示例是否存在。 (例如,参见WikiLight)
- 继续现有的,但对如何正确实现
WikiInfo 类进行一些研究。请参阅 Gson 文档以开始使用它,但带有 Map<String, Page> page 的对象将是一个好的开始。那么Page.java 包含private String title, extract;