我想通过 volley 库从 api 中获取数据。
我正在通过 Android 中的 Volley 类检索 JSON 对象和 Json Arrray。我知道如何获取请求,但我真的很难解析这个巨大的嵌套 json。
我想从列表中获取同义词和反义词
我想从 Synonmys Array 和 antonyms array 获取数据......这是 api 的链接。 链接
我的主要活动
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
// creating a new json object and
// getting each object from our json array.
try {
// we are getting each json object.
JSONObject responseObj = response.getJSONObject(i);
String word = responseObj.getString("word");
String phonetic = responseObj.getString("phonetic");
JSONArray jsonArray = responseObj.getJSONArray("meaning");
for (int k = 0; k < response.length(); k++) {
?? what to do here ????????
------------------------need help here-------------------------------
}
synonymsList.add(new synonymsModel(word,phonetic, synonyms,antonyms));
buildRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
queue.add(jsonArrayRequest);
}
模特班
public class synonymsModel {
String word, phonetic , antonyms, synonyms;
public synonymsModel(String word, String phonetic, String antonyms, String synonyms) {
this.word = word;
this.phonetic = phonetic;
this.antonyms = antonyms;
this.synonyms = synonyms;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getAntonyms() {
return antonyms;
}
public void setAntonyms(String antonyms) {
this.antonyms = antonyms;
}
public String getSynonyms() {
return synonyms;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
}
基本上你想将你的 json 转换为你的 java 对象模型。
首先,您需要一个适合您案例的映射库 这是迄今为止最好的Gson
其次,你需要创建一个你需要的模型。
我个人将它用于java类
完成所有 2 个设置后,您只需要做转换
Gson gson = new Gson();
String json = gson.toJson(anything); // serializes target to Json
YourClass your class = gson.fromJson(json, YourClass.class); //
您不必为 each 调用 loop for i ,而您可以映射 while 对象本身。