user3236231 user3236231 - 3 months ago 15
C# Question

C# Newtonsoft JSON Update Where

I want to update an JToken Value with something like where select.

JSON:
[
{
"Uid": "7775",
"MessageID": "<c86bee87-ad2f-ebe6-5f62-1879faf76716@xxx.de>",
"Mailbox": "INBOX",
"Subject": "asdfdsf",
"Seen": true,
"Date": "31.08.2016 17:24:42",
"Name": "asdasdasd",
"Attachments": "0"
},
{
"Uid": "7776",
"MessageID": "<d0a1ec7a-7ca4-b5b6-7d1f-968e42e262d4@xxx.de>",
"Mailbox": "INBOX",
"Subject": "sdfdsf",
"Seen": true,
"Date": "31.08.2016 17:35:05",
"Name": "asdfasdf",
"Attachments": "0"
},
{
"Uid": "7777",
"MessageID": "<8d74bd7e66889c2a423ce43d032fc1ce@xxx.net>",
"Mailbox": "INBOX",
"Subject": "xxxs",
"Seen": true,
"Date": "31.08.2016 17:47:24",
"Name": "xxxssw",
"Attachments": "0"
}
]


I've tried something like this, but I cant find any funktion for update: [!! Pseudo Code !!]

JToken storage = JToken.Parse(System.IO.File.ReadAllText("tmp\\mail\\index.txt"));

storage = storage.FirstOrDefault(o => (string)o["seen"] == "false").Update("seen", "true"); // Update(Field, NewValue)

storage.WriteToFile(...)

Answer
JArray array = JArray.Parse(yourJson);
JObject jo = (JObject)array.FirstOrDefault(token => !(bool)token["Seen"]);
// you could make an extension method for the remove/add sequence
jo.Property("Seen").Remove();
jo.Property("Subject").AddAfterSelf(new JProperty("Seen", true));
// write back to file array.ToString()