正在更新存储在文件中的JSON



我在一个文件中存储了一些JSON,如下所示。我想做的是找到Task2,将其状态从complete更改为deleted,然后将其保存回我从中获得的文本文件中。但就我的一生而言,我无法理解这一点。

这是我的JSON:

{
    "tasks": [
        {
            "task"     : "Task1",
            "quantity" : "(1)",
            "state"    : "incomplete",
            "changed"  : "never"    
        },
        {
            "task"     : "Task2",
            "quantity" : "(1)",                             
            "state"    : "complete",
            "changed"  : "never"                    
        },
        {
            "task"     : "Task3",
            "quantity" : "(1)",             
            "state"    : "deleted",
            "changed"  : "never"                    
        }
    ]
}

这是我迄今为止(使用Json.Net)的代码

using (StreamReader reader = new StreamReader(fileStream))
{
    string txt = reader.ReadToEnd();
    JObject jObject = JObject.Parse(txt);
    JArray tasks = (JArray) jObject["tasks"];
    ....
    reader.Close();
}

我需要什么代码才能更新JSON?

您可以使用Json.Net(http://json.codeplex.com/releases/view/89222)并将其引用添加到你的项目中,然后你就可以做这样的事情。。。

 [DataContract]
        public class TaskClass
        {
            [DataMember(Name="task")]
            public string task { get; set; }
            [DataMember(Name="quantity")]
            public string quantity { get; set; }
            [DataMember(Name="state")]
            public string state { get; set; }
            [DataMember(Name = "changed")]
            public string changed { get; set; }
        }
        [DataContract]
        public class Tasks
        {
            [DataMember(Name = "tasks")]
            public IEnumerable<TaskClass> tasks { get; set; }
        }
//and you can deserialize json :
    string json = "{"tasks":[{"task": "Task1","quantity": "(1)","state": "incomplete","changed": "never"},{"task": "Task2","quantity": "(1)","state": "complete","changed": "never"},{"task":"Task3","quantity": "(1)","state": "deleted","changed": "never" }]}";
            Tasks allTasks = new Tasks();
            allTasks = JsonConvert.DeserializeObject<Tasks>(json);
            foreach (TaskClass task in allTasks.tasks)
            {
                if (task.task.ToLower() == "task2")
                {
                    task.state = "deleted";
                }
            }
//and serialize it again as :
string value = JsonConvert.SerializeObject(objTasks);

你可以像这样轻松地完成你想要的:

// Read the JSON file 
string json = File.ReadAllText(fileName);
// Parse the JSON
JObject jObject = JObject.Parse(json);
JArray tasks = (JArray)jObject["tasks"];
// Find the first JObject in tasks having a "task" property with a value of "Task2"
// If such an object exists, set its "state" property to "deleted"
JObject task2 = (JObject)tasks.FirstOrDefault(a => a["task"].ToString() == "Task2");
if (task2 != null)
{
    task2["state"] = "deleted";
}
// Write the JSON back to the file
File.WriteAllText(fileName, jObject.ToString());

请注意,您需要在代码顶部包含using System.Linq;,才能访问FirstOrDefault()方法。

相关内容

  • 没有找到相关文章

最新更新