Search code examples
javajsonjson-simple

How to modify the value of a particular field in a JSON file using json-simple, after parcing the JSON file


I need to modify a particular value of a key in my json file, it is a nested JSON file and i have traversed till that key value pair but i'm not able to modify the value and don't know how to write back to the json.

Using json-simple to parse the JSON

This is the JSON file:

{
  "entity": {
    "id": "ppr20193060018",
    "data": {
      "relationships": {
        "productpresentationtolot": [
          {
            "id": "",
            "relTo": {
              "id": "",
              "data": {
                "attributes": {
                  "rmsitemid": {
                    "values": [
                      {
                        "source": "internal",
                        "locale": "en-US",
                        "value": "2019306"
                      }
                    ]
                  }
                }
              },
              "type": "lot"
            }
          }
        ]
      }
    },
    "type": "productpresentation"
  }
}

Reading it using below code:

JSONParser parser = new JSONParser();
reader = new FileReader("path.json");
JSONArray rmsArray =(JSONArray) rmsitemid.get("values");
for(Object obj2:rmsArray)
{
JSONObject tempObj1=(JSONObject)obj2;
System.out.println(tempObj1.get("value"));
}

I'm able to print what is there in value(Key) i.e., 2019306 but i don't have any idea how can i replace it with some other value and it should change the value in JSON file also.

Any help appreciated!


Solution

  • Here is a complete exmaple how to read and write using the simple-json library:

    // read from resource file
    JSONObject value;
    try (Reader in = new InputStreamReader(getClass().getResourceAsStream("/simple.json"))) {
        JSONParser parser = new JSONParser();
        value = (JSONObject) parser.parse(in);
    }
    JSONObject entity = (JSONObject) value.get("entity");
    
    // update id
    entity.put("id", "manipulated");
    
    // write to output file
    try (Writer out = new FileWriter("output.json")) {
        out.write(value.toJSONString());
    }
    

    The JSONObjects are basically Maps. So you can just put values inside.

    In order to create a JSON string again, use toJSONString(). In my example, I create a new output file. You could also override the original input file, though. But you have to write the file completely.