我有一个处理来自网络的API的android应用(Java)。
当前,该应用正在处理如下所示的JSON文件:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
我需要处理另一个JSON文件,但是它具有不同的结构:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
如何通过调整以下代码来处理第二个JSON文件?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
非常感谢您的帮助!
答案 0 :(得分:1)
看起来,在第一个json内,您将“联系人”作为对象数组,在第二个json内,您将“联系人”作为对象。在其中,您还有其他对象,简化版本如下:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
因此,您唯一需要手动检查的选项是“联系人”数组或对象,并根据其更改代码。 看起来像这样:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}