How to Update JSON value using Java

后端 未结 2 1468
無奈伤痛
無奈伤痛 2020-12-20 09:13

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

{ 
"msgType": "NEW",
"code":          


        
相关标签:
2条回答
  • 2020-12-20 10:01

    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

    0 讨论(0)
  • 2020-12-20 10:06

    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();
    
    0 讨论(0)
提交回复
热议问题