2012-07-16 78 views
0

我有一些JSON存儲在文件中,如下所示。我想要做的是找到Task2,將其狀態從complete更改爲deleted,然後將其保存回我從中獲得的文本文件。但對於我的生活,我無法弄清楚這一點。更新存儲在文件中的JSON

這裏是我的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什麼代碼的代碼?

回答

0

您可以使用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); 
0

可以完成你想要的東西很容易像這樣:

// 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()方法。