【问题标题】:Remove JSONobject from JSONarray in Android从 Android 中的 JSONarray 中删除 JSONobject
【发布时间】:2014-09-24 05:30:18
【问题描述】:

我有动态 JSON 字符串,我想从 android 中的 JSONARRAY 中删除最后一个 JSON 对象。这是我在 android 中的动态 JSON 字符串。我的 json 字符串是

("{\"findAllUsersResponse\": "+arguments[0].toString()+"}");

    {
    "findAllUsersResponse": [
        {
            "id": "kicJw2whXyuGjbNo936L",
            "name": "Fghhjj",
            "udid": "2AA120E3-7478-4AD4-9C68-9C0920669B84"
        },
        {
            "id": "NEF45TWNI6-Uc_r7938R",
            "name": "ssss",
            "udid": "1DD083C2-7F1D-4BB3-9AB9-691A5FD251CC"
        },
        {
            "id": "xuXY7Ah2-O-jL4Zk939D",
            "name": "Test",
            "udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
        },
        {
            "id": "w1FnBz8B9ciWUzBk939k",
            "name": "Aditi",
            "udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
        }

    ]
}

【问题讨论】:

  • jsonArray.remove(jsonArray.length()-1);
  • 但我有动态 Json 字符串。我只想删除最后一个 JSON 对象
  • 对不起,我想在 API19 之前做...
  • @raja- 我想在 API 19 之前完成

标签: android json android-layout


【解决方案1】:

如果您的字符串不会更改并且您只想删除最后一个对象,请使用 substring 并创建新字符串。

 String finduserjson=  "{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
    String t = finduserjson.substring(finduserjson.indexOf("{"), finduserjson.lastIndexOf(",{"));
    String j = "]}";
    finduserjson = t+j;

干杯

【讨论】:

    【解决方案2】:

    遇到了类似的问题。 JSONarray 对象中没有方法可以得到你想要的。您可以创建一个功能来删除它。在某处看到了这个解决方案。

       public static JSONArray remove(final int index, final JSONArray from) {
        final List<JSONObject> objs = getList(from);
        objs.remove(index);
    
        final JSONArray jarray = new JSONArray();
        for (final JSONObject obj : objs) {
            jarray.put(obj);
        }
    
        return jarray;
    }
    
    public static List<JSONObject> getList(final JSONArray jarray) {
        final int len = jarray.length();
        final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
        for (int i = 0; i < len; i++) {
            final JSONObject obj = jarray.optJSONObject(i);
            if (obj != null) {
                result.add(obj);
            }
        }
        return result;
    }
    

    干杯!

    【讨论】:

      【解决方案3】:

      如果你使用JSON 而不是GSONJACKSON,那么你不能调用.remove() 方法,因为你不会在那里找到它。

      您能做的最好的事情是重新创建一个新的JSONArray 并在其中添加所需的JSONObjects

      【讨论】:

      • 但是兄弟响应来自服务器,我想每次都删除最后一个 json 对象。
      • 没关系。你用的是什么 JSON 库?
      • 所以你的意思是说不可能。
      • 我的意思是,使用 JSON.org 库这是无法做到的。如果您正在使用其他库(实际上应该这样做),那么您需要做的就是调用类似 foo.remove(foo.size() - 1);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2015-09-13
      • 2016-07-22
      相关资源
      最近更新 更多