Удалить дочерний атрибут из файла json

У меня есть следующий HTTP JSON-ответ в Java, который представляет объект пользователя.

{
    "account": "Kpatrick",
    "firstname": "Patrick",
    [
    ],
    "instances":
    [
        {
            "id": "packerer-pool",
            "key": "packerer-pool123",
            "userAccount": "kpatrick",
            "firstname": "Patrick",
            "lastname": "Schmidt",

        }
    ],
    "projects":
    [
        {
            "id": "packerer-projectPool",
            "projectKey": "projectPool-Pool",
            "cqprojectName": "xxxxx",
        },
       {
            "id": "packerer-secondproject",
            "projectKey": "projectPool-Pool2",
            "cqprojectName": "xxxx",

        },
        {
            "id": "packerer-thirdproject",
            "projectKey": "projectPool-Pool3",
            "cqprojectName": "xxxx",
        }
    ],

    "clients":
    [
    ],
    "dbid": 76864576,
    "version": 1,
    "id": "dbpack21"
}

Теперь я хочу найти конкретный проект с помощью projectkey (например, "projectPool-Pool2"). После этого я хочу полностью удалить элемент. Потому что моя цель - отправить HTTP-пост-звонок без этого проекта.

Результат должен быть похож на приведенный ниже для моего HTTP-вызова:

    {
    "account": "Kpatrick",
    "firstname": "Patrick",
    [
    ],
    "instances":
    [
        {
            "id": "packerer-pool",
            "key": "packerer-pool123",
            "userAccount": "kpatrick",
            "firstname": "Patrick",
            "lastname": "Schmidt",

        }
    ],
    "projects":
    [
        {
            "id": "packerer-projectPool",
            "projectKey": "projectPool-Pool",
            "cqprojectName": "xxxxx",
        },
        {
            "id": "packerer-thirdproject",
            "projectKey": "projectPool-Pool3",
            "cqprojectName": "xxxx",
        }
    ],

    "clients":
    [
    ],
    "dbid": 76864576,
    "version": 1,
    "id": "dbpack21"
}

Сначала я проанализировал ответ на строку.

    private static String getContent(HttpResponse response) {
    HttpEntity entity = response.getEntity();
    if (entity == null) return null;
    BufferedReader reader;
    try {
        reader = new BufferedReader(new InputStreamReader(entity.getContent()));
        String line = reader.readLine();
        reader.close();
        return line;
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

И сейчас я пытаюсь найти конкретный проект, но я не знаю, как продолжить.

String StringResponse = getContent(JsonResponse);
JSONObject jsonObject = new JSONObject(StringResponse);
JSONArray ProjectsArray= jsonObject.getJSONArray("projects");

Это правильный подход?

С уважением!

1 ответ

Решение

Когда у вас есть массив, попробуйте что-то вроде...

// Array to store the indexes of the JSONArray to remove
ArrayList<Integer> indexesToRemove = new ArrayList<Integer>();
// Iterate through projects array, check the object at each position
// if it contains the string you want, add its index to the removal list
for (int i = 0; i < projectsArray.length; i++) {
    JSONObject current = projectsArray.get(i);
    if (current.get("projectKey") == "**DESIRED PROJECT KEY**") {
        indexesToRemove.add(i);
    } 
}

Теперь вы можете перебирать свои индексы для удаления и удалять соответствующий объект из массива с помощью метода удаления JSONArrays (не уверен, как он называется, приведенный выше код из памяти). Обязательно удалите свои элементы НАЗАД, в противном случае вы удалите более ранние элементы, что изменит индексы, в результате чего вы удалите неправильный элемент, если затем удалите другой индекс.

// Going through the list backwards so we can remove the highest item each 
//time without affecting the lower items
for (int i = indexesToRemove.size()-1; i>=0; i--) {
    projectsArray.remove(indexesToRemove.get(i));
}
Другие вопросы по тегам