【问题标题】:Unique Sub-JSon object of a Json object in C#C#中Json对象的唯一Sub-JSon对象
【发布时间】:2017-09-07 17:25:30
【问题描述】:

让我从一个像这样的 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)? 谢谢大家。

【问题讨论】:

    标签: json linq c#-4.0


    【解决方案1】:

    您可以使用 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,结果打印出来了 http://csharppad.com/gist/5a39f78b1878738fa0181495bb6e3f6e

    【讨论】:

    • 谢谢!我能够使您的代码适应我的“真实”情况,并且效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2012-08-29
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多