如何使用org.json.simple从json数组中删除json对象



我有一个JSON文件,它是一个带有一些JSON对象的JSON数组,如果经度或纬度的值是空字符串",我想删除整个json对象。

我正在使用库org.json.simple。这是我的 json 文件:

[ {       "Longitude": 9.96233,
"Latitude": 49.80404 },

{
"Longitude": 6.11499,
"Latitude": 50.76891

},
{      "Longitude": 6.80592,
"Latitude": 51.53548
},
{
"Longitude": 9.50523,
"Latitude": 51.31991   },
{
"Longitude": ""
"Latitude": ""

},
{
"Longitude": 9.93368,
"Latitude": ""

},
{
"Longitude": 11.56122,
"Latitude": 48.14496

},
{
"Longitude": 13.34253,
"Latitude": 52.5319

},
{
"Longitude": 6.11327,
"Latitude": 50.77715

},
{
"Longitude": ""
"Latitude": ""
}
]

这就是我被困住的地方。 :

JSONParser jsonParser = new  JSONParser();
try (FileReader reader = new FileReader ("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node -> {
String vari = (String)((JSONObject)node).get("longitude").toString();            
if (vari==null) {
((JSONObject) node).remove();
System.out.println("deleted");          
}
}
...

任何建议如何更改我的代码?

您需要从列表中删除节点,但由于并发修改问题(修改您正在循环的列表(,您需要另一个列表。

我认为最简单的方法是将所有符合条件的节点收集到新列表中,例如:

@SuppressWarnings("unchecked")
@Test
public void test() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray listNonNull = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>)list).forEach(node -> {
// here any check that qualifies the node like also checking "Latitude"
// Also no need to cast to a String
Object vari = node.get("Longitude");
if (vari != null && !vari.equals("")) {
listNonNull.add(node);
}
});
} catch (Exception e) {
throw e;
}
}

如果希望仅使用原始列表,则可以收集要删除到另一个列表中的项目,并使用它来从原始列表中删除节点:

public void test2() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray toBeRemoved = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>) list).forEach(node -> {
Object vari = node.get("Longitude");
// here any check that qualifies the node like also checking "Latitude"
if (vari != null && !vari.equals("")) {
return; // not to be removed
}
toBeRemoved.add(node);
});
list.removeAll(toBeRemoved);
} catch (Exception e) {
throw e;
}
}

在代码中使用.remove而不是.clear

JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
ArrayList<JSONObject> objList = (ArrayList<JSONObject>) list.stream().filter(node -> {
String longitude = ((JSONObject) node).get("Longitude").toString();
String latitude = ((JSONObject) node).get("Latitude").toString();
if (longitude.isEmpty() || latitude.isEmpty()) {
return false;
}
return true;
}).collect(Collectors.toList());
} catch (IOException | ParseException e) {
e.printStackTrace();
}

最新更新