我有一个现有的JSON文件,它只包含简单的占位符JSON数组。我希望能够添加到特定的JSON数组。这是我的代码:
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));
这给了我一个输出到控制台:
[
[
"eventnumber",
"time",
"type",
"location",
"summary"
],
"eventNumber",
"Time",
"Type",
"Location",
"Summary"
]
而我想要制作的东西看起来更像是这样:
[
[
"eventnumber",
"time",
"type",
"location",
"summary"
],
[
"eventNumber",
"Time",
"Type",
"Location",
"Summary"
],
]
感谢您的帮助!
答案 0 :(得分:0)
在添加到incomingEvents
之前,需要将newEvent对象转换为JArray对象 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));