1

I have a JSON file which is an JSON ARRAY with some JSON Objects and I want to remove the entire json Object if the value of longitude or latitude is an empty string "".

I am using the library org.json.simple. Here is my json file:

  [ {       "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": ""
        }
     ]

and here's where I am stuck. :

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");          
        }
    }
    ...

Any suggestions how can I change my code ?

1
  • 2
    According to your JSON file, the structure is not an array of objects. All the objects are wrapped within a single object and that object is added to the array. So, in effect there is only one element in your list. Please validate your JSON using json editor. Commented Jul 3, 2020 at 9:36

3 Answers 3

1

You need to remove the node from the list but because of concurrent modification problem (modifying the list you are looping) you need another list.

I think it is easiest to collect into the new list all the nodes that qualify so like:

@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;
    }
}

If you wish to use only the original list you can collect items to be removed to an another list and use it to remove nodes from the original list:

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@ pirho Thank you for your reply, should I replace my list with this one? because I'm also doing some modification on the previous list so I have to use the same list with its nodes. should I add this method to my script and call it in the main ?
because when I tried to use it I got many errors in my code.
I can modify my answer to keep the original list. But somehow i think that you should do this mod first and only hten the rest to avoiid looping elems you actually remove later. So replase the list with the new one if you can do this as the very first mod. @Paupiette
1

use .remove instead of .clear in the code.

1 Comment

I've tried to use remove() but it only removes the key, I cant to remove the entire object.
0
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();
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.