user6942999
user6942999

Reputation:

Adding JSON Array to already existing JSON

I have an existing JSON file that just contains simple place holder JSON arrays. I would like to be able to add to the specific JSON arrays. Here is my code:

List<string> newEvent = new List<string>();
newEvent.Add(msg.Split('|')[1]);
newEvent.Add(msg.Split('|')[2]);
newEvent.Add(msg.Split('|')[3]);
newEvent.Add(msg.Split('|')[4]);
newEvent.Add(msg.Split('|')[5]);
JObject jsonObject = JObject.Parse(File.ReadAllText("data.json"));
JArray incomingEvents = jsonObject["incomingEvents"].Value<JArray>();
incomingEvents.Add(newEvent);
Console.WriteLine(JsonConvert.SerializeObject(incomingEvents, Formatting.Indented));

Which gives me an output to the console of:

[
  [
    "eventnumber",
    "time",
    "type",
    "location",
    "summary"
  ],
  "eventNumber",
  "Time",
  "Type",
  "Location",
  "Summary"
]

Whereas what I am trying to produce would look more like this:

[
  [
    "eventnumber",
    "time",
    "type",
    "location",
    "summary"
  ],
  [
    "eventNumber",
    "Time",
    "Type",
    "Location",
    "Summary"
  ],
]

Thanks for your help!

Upvotes: 0

Views: 8695

Answers (1)

Alex Nguyen
Alex Nguyen

Reputation: 1080

You need to convert your newEvent object to JArray Object before you add to incomingEvents

 List<string> newEvent = new List<string>();
        newEvent.Add(msg.Split('|')[1]);
        newEvent.Add(msg.Split('|')[2]);
        newEvent.Add(msg.Split('|')[3]);
        newEvent.Add(msg.Split('|')[4]);
        newEvent.Add(msg.Split('|')[5]);

        JArray newEventJsonItem = new JArray(newEvent);//Convert newEvent to JArray.

        JObject jsonObject = JObject.Parse(File.ReadAllText("data.json"));

        JArray incomingEvents = jsonObject["incomingEvents"].Value<JArray>();

        incomingEvents.Add(newEventJsonItem );//Insert new JArray object.

        Console.WriteLine(JsonConvert.SerializeObject(incomingEvents, Formatting.Indented));

Upvotes: 2

Related Questions