c#向Json文件添加新条目

时间:2016-05-16 13:23:00

标签: c# json json.net

我试图将成员添加到Json文件,但我无法弄清楚如何将新成员添加到现有文件。

{
  "Members": {
    "Example1": {
      "LastOnline": "2016-05-16T12:09:04.6459345Z",
      "TimeUntillEx": "2016-05-16T12:09:04.6459345Z",
      "Paied": true
    },
  }
}

问题是"示例1"已经是用户名。我不知道我是否应该尝试添加更多内容或复制现有内容并编辑复制的文本。 希望有人可以提供帮助。

顺便说一句。我很抱歉任何错误

1 个答案:

答案 0 :(得分:1)

首先,我要做的是将Members属性更改为array而不是object。然后,我会做这样的事情:

//original json. Notice that I added '[ ]' to make it an array
var json = "{ 'Members': " +
             "[ " +
                 "{'Example1': " +
                     "{ 'LastOnline': '2016-05-16T12:09:04.6459345Z', " +
                       "'TimeUntillEx': '2016-05-16T12:09:04.6459345Z', " +
                       "'Paied': true" +
                     "}, " +
                 "} " +
             "] " +
           "}";

//new member
var newMember = "{ 'Example2': " +
                    "{ 'LastOnline': '2016-12-16T12:09:04.6459345Z', " +
                      "'TimeUntillEx': '2016-12-16T12:09:04.6459345Z', " +
                      "'Paied': false" +
                    "}, " +
                "}";

//parse the json
var obj = JObject.Parse(json);

//get members array
var array = obj.GetValue("Members") as JArray;

//parse the new member and add it to the array
var add = JObject.Parse(newMember);

array.Add(add);

//serialize the json
var output = JsonConvert.SerializeObject(obj, Formatting.Indented);

//print the results
Console.WriteLine(output);

为此,您需要

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

enter image description here