Add a new entry to the json file

别等时光非礼了梦想. 提交于 2020-02-06 16:14:07

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/59241272/add-a-new-entry-to-the-json-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!