C#中Json对象的唯一Sub-JSon对象

时间:2017-04-12 05:24:49

标签: json linq c#-4.0

让我从像

这样的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)? 谢谢大家。

1 个答案:

答案 0 :(得分: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; }
}

以下是按作曲家ID和姓名分组的代码,并为每个小组选择第一个,这将确保您拥有唯一的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,结果打印出Getting started with Ansible