2017-02-28 73 views
1

如果ID等於2,如何將CourseNameHistory更改爲Gym更改特定屬性

{ 
    "Result": { 
    "StudentInfo": { 
     "ID": 20, 
     "Name": "Bob", 
     "IgnoreThis": [ 
     { 
      "ID": 123, 
      "Something":"abc" 
     } 
     ] 
    }, 
    "Courses": [ 
     { 
     "ID": 1, 
     "CourseName":"Math" 
     }, 
     { 
     "ID": 2, 
     "CourseName":"History" 
     } 
    ] 
    } 
} 

下面這段代碼只不過是一個虛幻的代碼來說明我的腦子裏想的:

{ "Result":{ "Course" : [ if id=2 inside "Courses" then "CourseName":"Gym" ] }} 

我將使用Postman

+1

您使用的是哪種編程語言? –

+0

@JonathanPortorreal C#,我試圖通過在Postman應用程序中使用JSON來實現這一點,然後在我的項目的C#上解決此問題。 – ipid

+0

對此使用Json.NET –

回答

0

這是一個解決方案,它可能會被整理出來。但是它使用Newtonsoft.Json(着名的nuget包)。

using System.Linq; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string blah = "{'Result': { 'StudentInfo': { 'ID': 20, 'Name': 'Bob', 'IgnoreThis': [{'ID': 123,'Something':'abc'}]}, 'Courses': [{'ID': 1,'CourseName':'Math'},{'ID': 2,'CourseName':'History'}]}}"; 

      dynamic json = JsonConvert.DeserializeObject(blah); 
      var dynamicJson = json.Result.Courses; // included to show how dynamic could be accessed instead 

      JObject arr = json; 

      foreach (var course in arr["Result"]["Courses"].Where(x => x["ID"].Value<int>() == 2)) 
      { 
       course["CourseName"] = "Gym"; 
      } 

      var newResult = json.ToString(); 
     } 
    } 
}