Using JsonObject

Updating Json Objects

Json objects can be updated at runtime.

For example, using the following JSON:

{
  "storeName": "Costco",
  "products": [
     {
         "id": 1,
         "name": "Apple iPhone",
         "price": 499.0
     },
     {
         "id": 2,
         "name": "Google Pixel"
     },
  ] 
}
JsonObject json = JsonParser.Parse(jsonText);

int numProducts = json["products"].AsArray().Length;

json["products"][numProducts]["id"] = 3;
json["products"][numProducts]["name"] = "Moto G6";
json["products"][numProducts]["price"] = 199.0;

Whenever a property is updated (either an element in an array or a field), it is either updated or created if it doesn't exist. In the example above, a new product is added to the array.

The code above could also be written like this:

int numProducts = json["products"].AsArray().Length;

var jsonProduct = JsonObject.EmptyObject();

jsonProduct["id"] = 3;
jsonProduct["name"] = "Moto G6";
jsonProduct["price"] = 199.0;

json["products"][numProducts] = jsonProduct;