1

Im trying to add Members to a Json file but i cant quite figure out how to add new Members to the Existing file.

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

Problem is "Example1" is already the Name of the User. I dont know if i should try to just add more or copy the existing and edit the copied text. Hope someone can Help.

btw. im new so sorry for any mistakes

Marlon Haenen
  • 13
  • 1
  • 3

1 Answers1

1

First, what I would do is change the Members property to be an array instead of an object. Then, I would do something like this:

//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);

For this, you will need

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

enter image description here

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
  • 1
    Thank you. this is just what i needed! – Marlon Haenen May 16 '16 at 16:26
  • Btw is there an easy way to remove an entry aswell ? – Marlon Haenen May 16 '16 at 17:55
  • Sure @MarlonHaenen. First, if you liked the answer don't forget to upvote it as well. Basically because you are using `Newtonsoft.Json.Linq`. You have the power to manipulate `JObject`s and `JArray`s as any other generic `C#` object. So, if you would like to remove something from the array. I would go and do something like: `array.RemoveAt(1);` //this would remove the entry that we just added or you could do something like `array.Remove(add);` //that would remove the object we just added. Don't forget to serialize the object at the end though. – Luis Lavieri May 16 '16 at 18:02
  • sadly i cant upvote since my reputation is too low O.o – Marlon Haenen May 16 '16 at 21:05