向json文件添加一个新条目 [英] Add a new entry to the json file

查看:92
本文介绍了向json文件添加一个新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的JSON文件:

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"
    }

我忘了说我不知道​​JSON的所有字段,因此,我不能使用类进行反序列化.

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

我已经尝试了在stackoverflow中找到的一千个代码,但是大多数代码仅用于添加单个字段或编辑现有字段的值.我在vb.net上使用Newtonsoft

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

我将不胜感激.

推荐答案

不使用类进行添加的一种方法是创建一个JObject并将其插入到个人档案中.

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;

自从您提到我不知道JSON的所有字段"以来,就很难使用一种方法来实例化配置文件(例如,每次使用一种方法来创建相同的对象,但是如果方法不同,它将具有手动创建和插入.

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.

要从内部元素中删除obj,请使用Property和Remove().如果要包括检查空对象,请使用?.Remove().

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

这篇关于向json文件添加一个新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆