0

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!

1
  • Show me what is in the data.json and what is in the msg variable. Commented Dec 12, 2017 at 3:00

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.