0

I have below json, i want to update each and every value of that json but sometimes only one value

{ 
"msgType": "NEW",
"code": "205",
"plid": "PLB52145",
}

I've already tried to update using below code

FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

System.out.println(jsonObject);


long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(plid);


idNewObj.put("plid",PL809809809);

System.out.println(jsonObject);
2
  • 3
    What was the output? What is the issue? Commented Oct 19, 2020 at 7:02
  • value weren't changed , so below solution is given to write the values. it works :) Thanks @papaya Commented Oct 20, 2020 at 10:29

2 Answers 2

1

You need to write the updated JSON into the file from where JSON was read. Also, I did not understand your variable assignment so I have updated that as well. Use below code:

FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

System.out.println(jsonObject);


long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(id);


jsonObject.put("plid",PL809809809);

System.out.println(jsonObject);
FileWriter writer = new FileWriter(filePath, false); //overwrites the content of file
writer.write(jsonObject.toString());
writer.close();
Sign up to request clarification or add additional context in comments.

4 Comments

Can anyone let me know why my answer got a downvote?
first of all don't know who downvoted your anwser....... tried above code, but at writer.write(jsonObject); i'm getting error write(int) in the type OutPutStreamWriter is not applicable for the arguments (JSONObject)
@Dhananjay_Khade I have edited my answer, this will work! FileWriter.write(...) accepts String argument, hence, changed it to writer.write(jsonObject.toString());
Thanks for the answer... i have already done this but it's printing in string format and it's changing the format of json like sequence of json objects...is it fine if sequence is changed ?
0

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

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.