使用jackson从文件中的Json数组中删除对象

我的JSON外观如下所示,我需要从中删除第一个对象secondArray。


{

   "firstArray":[

      {

         "data1":1,

         "data2":"DATA"

      },

      {

         "data1":2,

         "data2":"DATA2"

      }

   ],

   "secondArray":[

      {

         "number":1,

         "data":"DATA3",


      },

      {

         "number":2,

         "data":"DATA4"

      }

   ]

}

这是我到目前为止所拥有的:


public boolean remove(SecondArray object) {

 try {

  ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);

  ArrayNode array = (ArrayNode) root.get("secondArray");

  if (array.path("number").asInt() == object.getId()) {

   movieArray.remove(object.getId());

  }

  System.out.println(array.toString());


 } catch (IOException e) {

  e.printStackTrace();

 }

}

我的问题是object.getId()得到了idas 数字,但JSON它在“”里面。我该如何进行这项工作,以便我可以删除从中输入的对象secondArray?


茅侃侃
浏览 211回答 1
1回答

蝴蝶刀刀

不要删除数组item。object.id删除它index。您需要遍历数组,找到JSON Object位置number = object.id并将其删除。例子:import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import java.io.File;public class JsonApp {&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; File jsonFile = new File("./resource/test.json").getAbsoluteFile();&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);&nbsp; &nbsp; &nbsp; &nbsp; ArrayNode array = (ArrayNode) root.get("secondArray");&nbsp; &nbsp; &nbsp; &nbsp; int numberToRemove = 1;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array.get(i).get("number").asInt() == numberToRemove) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array.remove(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(array);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(root);&nbsp; &nbsp; }}上面的代码打印:[{"number":2,"data":"DATA4"}]{"firstArray":[{"data1":1,"data2":"DATA"},{"data1":2,"data2":"DATA2"}],"secondArray":[{"number":2,"data":"DATA4"}]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java