1

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!

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
Shilpa
  • 13
  • 1
  • 4
  • you can use Jackson framework. First of all you have to convert Json string to your Object. Once you get the object, you can modify whatever you want. – Sambit May 13 '19 at 09:10
  • 2
    Use ``jsonObject.put(key, value)`` to replace the old value with the one that you want. After that, convert the object back to string and write the string to the file – Thai Doan May 13 '19 at 09:16

1 Answers1

0

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.

Jochen Reinhardt
  • 833
  • 5
  • 14
  • This bit of code especially try (Writer out = new FileWriter("output.json")) { out.write(value.toJSONString()); } – Shilpa May 13 '19 at 10:05