我对解析 JSON 对象不是很熟悉,我真的需要你们的帮助。我知道我正在做的解析是错误的,并且在在线阅读有关在 Android Studio 中解析的资源后我不明白。
下面的代码是我的项目的解析部分。
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("translations");
for (int i = 0; i < jsonArray.length(); i++ ) {
JSONObject translations = jsonArray.getJSONObject(i);
String translatedText = translations.getString("translatedText");
textView.append(translatedText);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我试图解析的 JSON 对象如下:-
{
"data": {
"translations": [
{
"translatedText": "queso"
}
]
}
}
我被告知我的代码不起作用,因为 JSON 的第一级是 JSONObject“数据”而不是“翻译”,但我不知道如何将代码修改为应该如何?
自从我使用内置的 Android JSON 对象已经有一段时间了,但我最初的反应是您需要在解析 JSON 数组“translations”之前解析 JSON 对象“data”。修改您之前的代码:
public void onResponse(JSONObject response) {
try {
JSONObject data = response.getJSONObject("data"); // get data first
JSONArray jsonArray = data.getJSONArray("translations"); // get the array from data
for (int i = 0; i < jsonArray.length(); i++ ) {
JSONObject translations = jsonArray.getJSONObject(i);
String translatedText = translations.getString("translatedText");
textView.append(translatedText);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句