HeberonYT
HeberonYT

Reputation: 33

Add a new entry to the json file

I have a JSON file with the following format:

    {
      "profiles": {
        "Profile1": {
          "name": "Nombre 1",
          "lastVersionId": "14.23.5.2838",
          "javaArgs": "-Xmx8G"
        },
        "Profile2": {
          "name": "Nombre 2",
          "lastVersionId": "58.96.004",
          "javaArgs": "-Xmx8G"
        }
      },
      "selectedProfile": "Profile1"
    }

I need to add a new profile, that is, add this entire block:

    "Profile3": {
      "name": "Nombre 3",
      "lastVersionId": "58.96.004",
      "javaArgs": "-Xmx8G"
    }

I forgot to say that I don't know all the fields of JSON, therefore, I can't use classes to deserialize.

I have tried a thousand codes that I found in stackoverflow but most are for adding only individual fields or editing the values of existing fields. I am using Newtonsoft on vb.net

I would appreciate all the help possible.

Upvotes: 0

Views: 169

Answers (1)

Jawad
Jawad

Reputation: 11364

One way to add without using classes would be to create a JObject and insert that to the Profiles.

    dynamic jsonObject = JsonConvert.DeserializeObject(json);

    var profile3 = new JObject
    {
        ["name"] = "Nombre 3",
        ["lastVersionID"] = "58.96.004",
        ["javaArgs"] = "-Xmx8G"
    };
    jsonObject["profiles"]["Profile3"] = profile3;

Since you mentioned, " I don't know all the fields of JSON", it becomes hard to use a method to instantiate a profile (like using a method to create same object each time but if its different, it will have to be manually created and inserted.

EDIT: To remove an obj from inside elements, use Property and Remove(). If you want to include checking the null objects, use the ?.Remove().

jsonObject["profiles"].Property("Profile3")?.Remove();



Edit 2: You can check if the Profile exists before updating as well.

Console.WriteLine(jsonObject["profiles"]["Profile4"] != null);

// output:
False

Upvotes: 1

Related Questions