繁体   English   中英

从json响应Android中删除对象

[英]Remove object from json response Android

大家好,我需要您的帮助。 如何从json响应中删除此内容?

[
  {
    "Woa": [
        "Seo",
        "Rikjeo",
        "JDa"
    ]
  },
"Aha",
"Aad",
"Char"
]

我要删除此:

{
    "Woa": [
        "Seo",
        "Rikjeo",
        "JDa"
    ]
  }

这是我到目前为止尝试过的:

for (int i = 0; i < array.length(); ++i) {
    list.add(array.getString(i));
}

list.remove(0);

但是它仍然没有被删除。 我怎么做? 任何想法将不胜感激

编辑list.remove(1)至(0)

删除项目后,您需要使用列表再次创建JSON。

list.remove(1);

JSONArray jsArray = new JSONArray(list);

如果要将JSONArray转换为JSON字符串:

jsArray.toString()

您的列表将被更新,而不是JSON对象。

为什么不使用JSONparser

JSONObject obj = new JSONObject(mystring);
obj.remove("entryname");

您应该做一些更通用的事情,这样就不必在每次JSON更改时都修改代码。 例如:

        //here we create the JSONArray object from the string that contains the json data
        JSONArray array = new JSONArray(myJsonString);

        //here we create a list that represents the final result - a list of Strings
        List<String> list = new ArrayList<>();

        //here we parse every object that the JSONArray contains
        for (int i = 0; i < array.length(); i++) {

            //if the current item is an JSONObject, then we don't need it, so we continue our iteration 
            //this check is not necessary because of the below check, 
            //but it helps you see things clearly: we IGNORE JSONObjects from the array
            if (array.get(i) instanceof JSONObject) {
                continue;
            }

            //if our current object is a String, we add it to our final result
            if (array.get(i) instanceof String) {
                list.add(array.getString(i));
            }
        }

一个问题是您要删除的元素是第一个,而JSONArray对象的第一个元素的索引为零。

您正在调用list.remove(1) ,它将删除数组的第二个元素。

以下内容就足够了:

list.remove(0);

...之前没有东西。

如果这不起作用,那么我的猜测是您将元素删除为时已晚; JSONArray对象已序列化之后。 但是,我们需要查看更多(相关)代码以确保。


Android文档JSONArray未能提及数组索引是从零开始的。 但是,确实如此。 我检查了源代码。 此外,大多数其他Java数据结构(数组,列表等)都使用基于零的索引。 (一个明显的例外是在W3C DOM API上建模的Java数据结构。)

您可以将字符串解析为JSONArray,数组的第一个元素就是您想要的。

@Test
public void test() {
    String str = "[  {\"Woa\": [\"Seo\",\"Rikjeo\",\"JDa\"]},\"Aha\",\"Aad\",\"Char\"]";
    try {
    JSONArray array;
        array = new JSONArray(str);
        System.out.println(array);
        System.out.println(array.get(0));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

[{“ Woa”:[“ Seo”,“ Rikjeo”,“ JDa”]},“ Aha”,“ Aad”,“ Char”]

{“ Woa”:[“ Seo”,“ Rikjeo”,“ JDa”]}

通过:测试

您可以一一删除

 while (user_data.length() > 0) {
  user_data.remove(user_data.keys().next());
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM