Jake C.
Jake C.

Reputation: 287

Overwrite JsonNode using Jackson

I am using the Jackson streaming api to read in a json file like so:

// Go through json model and grab needed resources.
            JsonFactory jsonfactory = new JsonFactory();
            JsonParser jp = jsonfactory.createParser(fis);
            JsonToken current;
            current = jp.nextToken();
            ObjectMapper mapper = new ObjectMapper();

            if (current != JsonToken.START_OBJECT) {
                System.out.println("Error: root should be object: quiting.");
                return null;
            }
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldName = jp.getCurrentName();
                // move from field name to field value
                if ("Field1".equals(fieldName)) {
                    jp.nextToken();
                    JsonNode json = mapper.readTree(jp);
                    //Manipulate JsonNode
                    /*Want to write back into json file in place of 
                     old object with manipulated node*/
                } 
                else {
                    jp.skipChildren();
                }
            }

From the code above I am basically parsing the json file until I find the desired field I am looking for and then I read that into a JsonNode object, I then go through that JsonNode object and manipulate some of the data associated with it. My question is is there a way to delete that node out of the json file and write a newly created POJO into the file with the same field name in place of the old one? Everything I can find online about it involve reading the whole json file into a JsonNode which I would like to avoid as this file can be quite large.

Upvotes: 1

Views: 795

Answers (1)

mrusinak
mrusinak

Reputation: 1092

In-place editing of a file like that is usually pretty complicated; a simpler approach is to create a new temporary file, and for the most part just copy what you're writing until you hit the conditions to modify what's going to the new one.

Then at the end you could delete the original file and rename the temporary one to "replace" it; Unless disk space is an issue though, I personally like keeping the original source around (especially in automated systems) for troubleshooting

Upvotes: 1

Related Questions