Android 从JSON对象中删除JSON对象的最佳方法
假设我有一个JSONObjectAndroid 从JSON对象中删除JSON对象的最佳方法,android,json,jsonobject,Android,Json,Jsonobject,假设我有一个JSONObject { "poll_answers":{ "213":{ "poll_answer_text":"Black", "poll_answer_id":"213" }, "214":{ "poll_answer_text":"White", "poll_answer_id":"214" },
{
"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"
}
}
}
移除**键为“214”的JSONObject(例如)的最相关/最佳方法是什么?因为androidremove方法返回键之前映射的值,但不返回给定对象(我要移除的对象除外)。因此,解决方案应该如下所示:
{
"poll_answers":{
"213":{
"poll_answer_text":"Black",
"poll_answer_id":"213"
},
"218":{
"poll_answer_text":"Colorful",
"poll_answer_id":"218"
}
}
}
remove()
方法是您想要的——但是,由于它包含在另一个JSONObject
中,因此您必须在更深的一层中导航:
JSONObject object = new JSONObject("your json string");
object.getJSONObject("poll_answers").remove("214");
否决票?请给出一个理由。我无意冒犯,但是如果我想删除对象
poll\u answers
?收到的对象将是{“213”:{“poll\u answer\u text”:“Black”,“poll\u answer\u id”:“213”},“218”:{“poll\u answer\u text”:“color”,“poll\u answer\u id”:“218”}
但我想要的是空对象{
。我应该使用循环来实现这一点吗?THXI如果您想删除poll\u answers
,只需使用object.remove(“poll\u answers”)
。只能删除所引用对象的直接子对象。