使用杰克逊从文件中的Json阵列中删除对象

时间:2019-02-27 22:55:51

标签: java json jackson

我的from selenium import webdriver; import csv; driver = webdriver.Firefox(); driver.get("https://www.betexplorer.com/baseball/usa/mlb-2018/results/? stage=KvfZSOKj&month=all") links_code : list = driver.find_elements_by_xpath('//a[@class="in-match"]'); first_two : list = links_code[0:2]; first_two_links : list = []; i : int; for i in first_two: link = i.get_attribute("href"); first_two_links.append(link); odds : list = []; i :int; for i in first_two_links: driver.get(i); o = driver.find_element_by_xpath('//span[@class="table-main__detail- odds--hasarchive"]'); odds.append(o); **Error:** NoSuchElementException: Message: Unable to locate element: //span[@class="table-main__detail- odds--hasarchive"] 如下所示,我需要从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()作为数字,但是在id中却出现在“”内。如何进行这项工作,以便可以删除从JSON输入的对象?

1 个答案:

答案 0 :(得分:0)

请勿通过item删除数组object.id。通过index将其删除。您需要遍历数组,在JSON Object的{​​{1}}中找到并删除它。示例:

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 {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);
        ArrayNode array = (ArrayNode) root.get("secondArray");

        int numberToRemove = 1;
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i).get("number").asInt() == numberToRemove) {
                array.remove(i);
                break;
            }
        }
        System.out.println(array);
        System.out.println(root);
    }
}