0

I have a code where this help me to update the JSON node values. But, there is a small complexity in my way of handling. I have a Node that may come across any JSONObject.

Note: Below is the sample json structure.

{              
    "Apple": {
        "Name": "AA",
        "description": "apple"
    },           
    "Mango": {
        "Name": "RA",
        "description": "Mango"
    }
}

I would like to update the Name and Description for both Apple and Mango.

Turing85
  • 18,217
  • 7
  • 33
  • 58
Danesh
  • 45
  • 10
  • 1
    And your question is ...? – Turing85 Aug 03 '19 at 18:44
  • I would like to update name and description for both apple and mango. How can I do that.. I am from Testing , so I am my not be able to describe it development terms.. sorry about that... – Danesh Aug 03 '19 at 19:04

2 Answers2

2

Before:

{
   "Apple":{
      "Name":"AA",
      "description":"apple"
   },
   "Mango":{
      "Name":"RA",
      "description":"Mango"
   }
}

With this code:

JsonObject Apple = myJson.getAsJsonObject("Apple");
Apple.addProperty("Name", "BB");
Apple.addProperty("description", "New apple");

You will get:

{
   "Apple":{
      "Name":"BB",
      "description":"New apple"
   },
   "Mango":{
      "Name":"RA",
      "description":"Mango"
   }
}
bart
  • 1,003
  • 11
  • 24
0

Use the put method: https://developer.android.com/reference/org/json/JSONObject.html

JSONObject apple =  jsonArray.getJSONObject(0).getJSONObject("apple");
person.put("Name", "Honeycrisp");

//Similarly
JSONObject apple =  jsonArray.getJSONObject(0).getJSONObject("apple");
person.put("description", "a sweet apple");
  • Thank you. But would like to see in java. I am working on creating a API framework. I will be given with request json and I would need to run with different values. I could find few solutions in stack overflow to update json using recursive function but when it comes to above scenario like updating description or name for different object, I am stuck . – Danesh Aug 03 '19 at 19:23
  • @Danesh I have updated my answer with the Java solution, sorry about that! – bashedandzshed Aug 03 '19 at 19:27