-2

This is my sample Json

 {
        "State": {
            "version": "1",
            "SName": "Test",
            "shippingDetails": {
                "Address1": "AP",
                "ZipCode": "1236"
            },
            "Directions": {
                "routes": [
                    {
                        "taxAmount": "0.0",
                        "Quantity": "5",
                        "bounds": {
                            "SerialVersion": [
                                {
                                    "text": "1.7 km",
                                    "value": "1729",
                                    "time": "02633"
                                },
                                {
                                    "text": "1.9 km",
                                    "value": "1829",
                                    "time": "02353"
                                },
                                {
                                    "text": "17 km",
                                    "value": "1059",
                                    "time": "02133"
                                }
                            ]
                        }
                    }
                ]
            }
        }
    }

I want to update SName, ZipCode,taxAmount,Quantity, and text[1] values are there any way to do this. I am taking JSON in a file and update tags are taking into HashMap

Siva
  • 113
  • 4
  • 13

1 Answers1

2
JSONObject jsonObject = new JSONObject("Your_JSON_String");

JSONObject jsonObjectForState = jsonObject.getJSONObject(“State”);

jsonObjectForState.put("Sname", "New_Value_Here");

put(...) will replace the current value with new value. Similarly, you can update the other values. Once you are done, you can convert it back using:

jsonObject.toString();

And write it back to the file.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • its not working and new tag is appending at outside of State{} – Siva Feb 26 '20 at 22:02
  • So that is from someone else who thinks the question might not help others in the future or the question quality is not upto the mark. In the future, please go through this before posting a question to avoid negative votes: https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ – Harshal Parekh Feb 28 '20 at 22:17