lincredibleJC
lincredibleJC

Reputation: 107

How to remove an element from a .json file?

I have a JSON file: "data.json" containing a JSONArray of about 600 objects that have attributes: alias, telephone, type, building and title. And I'm trying to remove all of the alias and telephone attributes from the objects in the array.

Here's a sample:

[
  {
    "Title": "7 Eleven",
    "Alias": "Seven Eleven",
    "Building": "7 Eleven"
  },
  {
    "Title": "Adaptive Computing Research Lab",
    "Alias": "acrl",
    "Type": "Faculty",
    "Building": "COM1"
  },
  {
    "Title": "Alcove.Asian Restaurant Bar",
    "Building": "University Cultural Centre"
  },
  {
    "Title": "Algorithms Research Lab",
    "Alias": "arl",
    "Type": "Faculty",
    "Building": "COM1"
  }
]

I understand that this is a JsonArray so I have to parse it is as a JsonArray type instead of a JsonObject so the parsing is not the problem. But when I use this code

import javax.json.*;
import java.io.FileNotFoundException;
import java.io.FileReader;

public static void main(String args[]) throws FileNotFoundException {

    JsonReader reader = Json.createReader(new FileReader("data.json"));
    JsonArray jsonArray = (JsonArray) reader.read();

    for (int i = 0; i < jsonArray.size(); i++) {

        JsonObject o = (JsonObject) jsonArray.get(i);

        if (o.containsKey("Alias"))
            o.remove("Alias");

        if (o.containsKey("Telephone"))
            o.remove("Telephone");

        System.out.println(jsonArray);
    }

}

I'm having this error

Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$1.remove(Collections.java:1664) at java.util.AbstractMap.remove(AbstractMap.java:254) at JSONEditor.main(JSONEditor.java:20)

I don't understand why it is Unmodifiable.

So far, I've looked through many other similar questions and answers on StackOverflow and documentation that suggest that what I'm trying to do is possible but I still don't understand why this isn't working out for me.

Upvotes: 0

Views: 3157

Answers (2)

SedJ601
SedJ601

Reputation: 13859

This is built on your current code. This code builds a new JSONArray that only has the data you want to keep.

    try 
    {
        File file = new File("data.json");
        if(file.exists())
        {
            System.out.println(file.getAbsolutePath());
        }
        JsonReader reader = Json.createReader(new FileReader("data.json"));
        JsonArray jsonArray = (JsonArray) reader.read();

        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
        //Build new json Array
        for (int i = 0; i < jsonArray.size(); i++) {  
            String titleData = jsonArray.getJsonObject(i).get("Title") != null ? jsonArray.getJsonObject(i).get("Title").toString() : "";            
            String buildingData = jsonArray.getJsonObject(i).get("Building") != null ? jsonArray.getJsonObject(i).get("Building").toString() : "";              
            String typeData = jsonArray.getJsonObject(i).get("Type") != null ? jsonArray.getJsonObject(i).get("Type").toString() : "";                                               
            JsonObject object = Json.createObjectBuilder().add("Title", titleData).add("Building", buildingData).add("Type", typeData).build();

            jsonArrayBuilder.add(object);               
        }

        JsonArray newJSONArray = jsonArrayBuilder.build();
        //print newJSONArray
        for(JsonValue jsonValue : newJSONArray)
        {
            System.out.println(jsonValue);
        }            
    }
    catch (FileNotFoundException ex) {
        System.out.println(ex.toString());
    }

Upvotes: 0

LazerBanana
LazerBanana

Reputation: 7211

Ok. This should help, its a widely known library Jackson Databind which you can use to work with your Json. below is the link to the library. https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.8.8.1

And here is the code that should help you. Note that the file I have put into src/main/resources

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Main {

    public static void main(String args[]) throws IOException {

        Main main = new Main();
        File file = main.getFile("data.json");
        ObjectMapper mapper = new ObjectMapper();

        JsonNode root = mapper.readTree(file);

        for (JsonNode jsonNode : root) {
            if (jsonNode instanceof ObjectNode) {
                ObjectNode o = (ObjectNode) jsonNode;
                o.remove("Alias");
                o.remove("Telephone");
            }
        }

        System.out.println(root);    
    }

    private File getFile(String fileName) {
        return new File(getClass().getClassLoader().getResource(fileName).getFile());
    }
}

Upvotes: 1

Related Questions