2017-04-12 71 views
0

让我从一个JSON对象开始喜欢独特的分JSON对象

[ 
    { 
    "id": 32837732, 
    "composer": { 
     "id": 536, 
     "name": "Francis Poulenc" 
    }, 
    "title": "Of Thee I Sing: Overture (radio version)" 
    }, 
    { 
    "id": 32837735, 
    "composer": { 
     "id": 245, 
     "name": "George Gershwin" 
    }, 
    "title": "Concerto in F : I. Allegro" 
    }, 
    { 
    "id": 32837739, 
    "composer": { 
     "id": 245, 
     "name": "George Gershwin" 
    }, 
    "title": "Concerto in F : II. Adagio" 
    } 
] 

是有可能得到,用C#,LINQ中,在干净的,声明的方式,一个JSON像

{ 
'composer': [ 
       { 
       'id': '536', 
       'name': 'Francis Poulenc' 
       }, 
       { 
       'id': '245', 
       'name': 'George Gershwin' 
       }, 
     ] 
} 

这是一个JSon对象,每个作曲者(id和name)都有唯一的子值吗? 感谢所有。

回答

0

您可以使用Newtonsoft.Json.JsonConvert,并且需要创建相应的类才能反序列化和序列化对象。

这是类会是什么样子

public class YourObject 
{ 
    public int id { get; set; } 
    public Composer composer { get; set; } 
    public string title { get; set; } 

} 

public class Composer 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
} 

public class JsonResult 
{ 
    public List<Composer> composer { get; set; } 
} 

在这里你作曲家编号和名称做1组,采取的第一个每个组的代码,这将确保您有唯一的ID的和名称

string jsonString = 
    "[\r\n {\r\n \"id\": 32837732,\r\n \"composer\": {\r\n  \"id\": 536,\r\n  \"name\": \"Francis Poulenc\"\r\n },\r\n \"title\": \"Of Thee I Sing: Overture (radio version)\"\r\n },\r\n {\r\n \"id\": 32837735,\r\n \"composer\": {\r\n  \"id\": 245,\r\n  \"name\": \"George Gershwin\"\r\n },\r\n \"title\": \"Concerto in F : I. Allegro\"\r\n },\r\n {\r\n \"id\": 32837739,\r\n \"composer\": {\r\n  \"id\": 245,\r\n  \"name\": \"George Gershwin\"\r\n },\r\n \"title\": \"Concerto in F : II. Adagio\"\r\n }\r\n]"; 
List<YourObject> yourList = JsonConvert.DeserializeObject<List<YourObject>>(jsonString); 
List<Composer> composers = yourList.Select(t => t.composer).GroupBy(t => new { t.name, t.id }).Select(t => t.First()).ToList(); 
JsonResult jsonResult = new JsonResult { composer = composers }; 
var jsonResultString = JsonConvert.SerializeObject(jsonResult); 

这里与结果的全csharppad打印出来http://csharppad.com/gist/5a39f78b1878738fa0181495bb6e3f6e

+0

谢谢!我能够将您的代码适应我的“真实”情况,并且完美地工作! –