使用JackSon删除JSONArray中的特定数组

问题描述 投票:0回答:1

我有这样的东西:

    { 
  "Person": {
    "Info": [
      "name":"Becky",
      "age": 14
    ]
  },
  "FruitsList": {
    "Fruits": [
      {
        "name": "avocado",
        "organic": true
      },
      {
        "name": "mango",
        "organic": true
      }
    ]
  },
  "VegetablesList": {
    "Vegetables": [
      {
        "name": "brocoli",
        "organic": true
      },
      {
        "name": "lettuce",
        "organic": true
      }
    ]
  }
}

我想删除数组FruitsList和VegetablesList甚至是Person数组。这样的事情。

{ 
  "Person": {
    "Info": [
      "name": "Becky",
      "age": 14
    ]
   },
  "Fruits": [
    {
      "name": "avocado",
      "organic": true
    },
    {
      "name": "mango",
      "organic": true
    }
  ],
  "Vegetables": [
    {
      "name": "brocoli",
      "organic": true
    },
    {
      "name": "lettuce",
      "organic": true
    }
  ]
}

我不太确定在JACKSON库中使用哪种方法来获得正确的结果。非常感谢您的帮助。提前致谢。

java jackson gson
1个回答
0
投票

一种简单的方法是先从根节点中删除FruitsListVegetablesList节点,然后如下所示将FruitsVegetables添加回去:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
JsonNode personNode = rootNode.get("Person");
JsonNode fruitsListNode = rootNode.get("FruitsList");
JsonNode vegetablesList = rootNode.get("VegetablesList");
((ObjectNode) rootNode).remove("FruitsList");
((ObjectNode) rootNode).remove("VegetablesList");
((ObjectNode) rootNode).put("Fruits", fruitsListNode.get("Fruits"));
((ObjectNode) rootNode).put("Vegetables", vegetablesList.get("Vegetables"));

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

顺便说一句,正如我在OP中所说,您的JSON字符串为invalid。有效的应该是"Person": {"Info": {...}},...

© www.soinside.com 2019 - 2024. All rights reserved.