0

Assuming that I have a JSONObject

{
    "poll_answers":{
        "213":{
            "poll_answer_text":"Black",
            "poll_answer_id":"213"
        },
        "214":{
            "poll_answer_text":"White",
            "poll_answer_id":"214"
        },
        "218":{
            "poll_answer_text":"Colorful",
            "poll_answer_id":"218"
        }
    }
}

what is the most relevant/best way to remove** a JSONObject with key "214" (for example) since the android remove method returns the value previously mapped by the key but not the given object excluding the object I want to remove. So the solution should look like:

{
    "poll_answers":{
        "213":{
            "poll_answer_text":"Black",
            "poll_answer_id":"213"
        },
        "218":{
            "poll_answer_text":"Colorful",
            "poll_answer_id":"218"
        }
    }
}
0

1 Answer 1

2

The remove() method is what you want -- however, you have to navigate in one level deeper since it's contained within another JSONObject:

JSONObject object = new JSONObject("your json string");
object.getJSONObject("poll_answers").remove("214");
Sign up to request clarification or add additional context in comments.

2 Comments

No offense here, but what if I wanted to remove the object poll_answers ? The object received would be {"213":{"poll_answer_text":"Black","poll_answer_id":"213"},"218":{"poll_answer_text":"Colorful","poll_answer_id":"218"}} but what I wanted was empty object {}. Should I use loops to achieve that? Thx
If you wanted to remove poll_answers, you would just use object.remove("poll_answers"). You can only remove direct children of the object you're referencing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.