How to Update JSON value using Java

To make transformation/filtering of JSON files, I’d suggest to use stream/event-oriented parsing and generating rather than any object mapping. Just an example, which uses simple and lightweight JSON parser https://github.com/anatolygudkov/green-jelly :

import org.green.jelly.AppendableWriter;
import org.green.jelly.JsonEventPump;
import org.green.jelly.JsonParser;

import java.io.StringWriter;
import java.io.Writer;

public class UpdateMyJson {
    private static final String jsonToUpdate = "{\n" +
            "\"msgType\": \"NEW\",\n" +
            "\"code\": \"205\",\n" +
            "\"plid\": \"PLB52145\",\n" +
            "}";

    public static void main(String[] args) {
        final StringWriter result = new StringWriter();

        final JsonParser parser = new JsonParser();
        parser.setListener(new MyJsonUpdater(result));
        parser.parse(jsonToUpdate); // if you read a file with a buffer,
        // call parse() several times part by part in a loop until EOF
        parser.eoj(); // and then call .eoj()

        System.out.println(result);
    }

    static class MyJsonUpdater extends JsonEventPump {
        private boolean isPlid;

        MyJsonUpdater(final Writer output) {
            super(new AppendableWriter<>(output));
        }

        @Override
        public boolean onObjectMember(final CharSequence name) {
            isPlid = "plid".contentEquals(name);
            return super.onObjectMember(name);
        }

        @Override
        public boolean onStringValue(final CharSequence data) {
            if (isPlid) {
                if ("PLB52145".contentEquals(data)) {
                    return super.onStringValue("PL809809809");
                }
            }
            return super.onStringValue(data);
        }
    }
}

Props:

  1. the file/data doesn’t require to be loaded entirely into memory, you can process megs/gigs with no problems
  2. it works much more faster, especially for large files
  3. it’s easy to implement any custom type/rule of transformation with this pattern

Both of standard Gson and Jackson libs also provide tokenizers to work with JSON in streaming manner.

UPDATED: JsonEventPump used

Leave a Comment