如何在运行时从 json 数组中删除完整条目

我想通过提供要删除的值在运行时删除 JSON 数组记录。


我已经尝试了以下代码,但它在每个值上添加一个;/


原始 json 文件:

{"Products":[{"p10":"SamsungS5"},{"i6":"Iphone6"}]}


执行删除操作后,输出变为:

{"Products":[["{\"p10\":\"SamsungS5\"}","{\"i6\":\"Iphone6\"}"]]}


remove 方法的代码为:


public static void removeSearchedClass(String value ) throws IOException, ParseException, InvocationTargetException {



        Object obj = new JSONParser().parse(new FileReader(FILE_NAME));

        JSONObject jo = (JSONObject) obj; 



        ArrayList<String> list = new ArrayList<String>();     

        JSONArray solutions = (JSONArray) jo.get("Products");

        int len = solutions.size();

        if (solutions != null) { 

           for (int i=0;i<len;i++){ 

            list.add(solutions.get(i).toString());

           } 

        }

                list.remove(value.trim());


        solutions.clear();

        solutions.add(list);


        jo.put("Products", solutions);


        FileWriter file = new FileWriter(FILE_NAME, false);

        file.append(jo.toString());

        file.flush();

        file.close(); 

         }

当我输入“iphone6”时,我需要IPHONE6的完整条目,即,将其删除。{"i6":"Iphone6"}


DIEA
浏览 161回答 1
1回答

喵喔喔

使用作为 JavaEE(现在的&nbsp;EE4J)规范一部分的&nbsp;JSON-P&nbsp;(JSR-374),您可以执行以下操作:String jsonString = "{\"Products\":[{\"p10\":\"SamsungS5\"},{\"i6\":\"Iphone6\"}]}";String removeValue = "\"Iphone6\"";JsonReader jsonReader = Json.createReader(new StringReader(jsonString));JsonObject jsonObj = jsonReader.readObject();JsonPatchBuilder builder = Json.createPatchBuilder();JsonArray jsonArray = jsonObj.getJsonArray("Products"); // [{"p10":"SamsungS5"},{"i6":"Iphone6"}]for (int i = 0; i < jsonArray.size(); i++) {&nbsp; &nbsp; JsonObject entry = jsonArray.get(i).asJsonObject();&nbsp; &nbsp; for (JsonValue value : entry.values()) {&nbsp; &nbsp; &nbsp; &nbsp; if (value.toString().equals(removeValue)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.remove("/Products/" + i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}JsonPatch patch = builder.build();JsonObject newObj = patch.apply(jsonObj);System.out.println(newObj); // {"Products":[{"p10":"SamsungS5"}]}“产品”数组包含 JSON 条目(键值对,如 )。然后循环访问每个条目的值(尽管只有一个:)。如果它与要删除的条目匹配,则可以修改修补程序以删除该条目的索引。然后在 JSON 对象上应用修补程序。{"i6":"Iphone6"}"Iphone6"依赖关系是规范,就像 JavaEE 一样:<dependency>&nbsp; &nbsp; <groupId>javax</groupId>&nbsp; &nbsp; <artifactId>javaee-api</artifactId>&nbsp; &nbsp; <version>8.0</version>&nbsp; &nbsp; <scope>provided</scope></dependency>和 JSON-P 的实现,如玻璃鱼:<dependency>&nbsp; &nbsp; <groupId>org.glassfish</groupId>&nbsp; &nbsp; <artifactId>javax.json</artifactId>&nbsp; &nbsp; <version>1.1.4</version></dependency>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java