我正在使用Rest States API来检索语言数据https://restcountries.eu/rest/v2/all ..,但由于数据位于数组中而没有显示语言。
这是我编写的用于使用Method.Get检索数据的代码
private void getCountriesList() {
String url = "https://restcountries.eu/rest/v2/all";
StringRequest request = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(!response.isEmpty()) {
Gson gson = new Gson();
JSONObject json = null;
// array of country
LanguageModel[] countries = gson.fromJson(response, LanguageModel[].class);
// add it to adapter
for(LanguageModel country: countries) {
mAdapter.addItem(country);
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getLocalizedMessage());
}
}
);
Volley.newRequestQueue(getApplicationContext()).add(request);
}
这是模型。检索国家名称时代码成功,但是检索语言数据时代码失败
public class CountryModel {
private String languages;
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}}
答案 0 :(得分:0)
我通过以下代码使用它:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject countryObj = mainArray.getJSONObject(i);
JSONArray languageArray = countryObj.getJSONArray("languages");
List<LanguageModel> languageModels = gson.fromJson(languageArray.toString(), new TypeToken<List<LanguageModel>>() {
}.getType());
// add it to adapter
for (LanguageModel languageModel : languageModels) {
//mAdapter.addItem(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// array of country
}
让我知道您是否仍然遇到错误。
修改:
但是如何同时获取国家/地区名称和语言?
您必须按照以下步骤编辑CountryModel
:
public class CountryModel {
@SerializedName("name")
String countryName;
@SerializedName("languages")
ArrayList<LanguageModel> languages;
public CountryModel() {
}
}
和LanguageModel
如下:
class LanguageModel {
@SerializedName("iso639_1")
String iso1;
@SerializedName("iso639_2")
String iso2;
@SerializedName("name")
String name;
@SerializedName("nativeName")
String nativeName;
public LanguageModel() {
}
}
现在是解析的最终更改:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
List<CountryModel> countryList = gson.fromJson(mainArray.toString(), new TypeToken<List<CountryModel>>() {
}.getType());
//do something with your country list
Log.d("R-Countries", countryList.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
虽然此答案有效,但您应该看到以下链接以了解我在这里所做的事情。
http://www.studytrails.com/java/json/java-google-json-introduction/