使用LINQ将JSON解析为对象列表

时间:2018-06-21 08:01:57

标签: c# json.net

我对解析以下JSON结构的最佳方法有些困惑。

{
"featured": {
    "id": 15,
    "title": "media 1 -> 7",
    "description": "test1",
    "short_description": "test1",
    "rating_avg": 0.0,
    "image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
},
"categories": [
    {
        "id": 1,
        "title": "category 0",
        "description": null,
        "position": 0,
        "media": [
            {
                "id": 1,
                "title": "media 0 -> 0",
                "description": "test1",
                "short_description": "test1",
                "rating_avg": 0.0,
                "image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
                "category_media": {
                    "position": 0,
                    "category_id": 1,
                    "media_id": 1,
                    "id": 1
                }
            }, ...

基本上,我有一个类别列表,其中包含一系列媒体(该功能用于其他用途)

我要返回List,并且Category对象包含一个List

我创建了一些模型:

public class Category
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    public List<Media> MediaList { get; set; }
}

public class Media
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string ShortDescription { get; set; }
    public string Image { get; set; }
}

..我应该使用Newtonsoft吗?

我看了下面的示例:Deserializing Partial JSON Fragments,但是我认为我不需要从JToken-> Category ...等进行转换。换句话说,我认为返回就很容易我的列表。

我是LINQ的新手(我来自python背景),所以我逐渐了解C#

5 个答案:

答案 0 :(得分:1)

在这种情况下,除非您想更改数据结构,否则不需要LINQ。要解析json文件以列出列表,您必须创建一个与文件结构匹配的类,例如:

class DataModel
{
      public Featured Featured { get; set; }
      public List<Category> Categories { get;set; }
}

此外,请注意,如果json中的属性名称与类中的属性名称不同,则需要使用属性[JsonProperty(PropertyName="fieldName")]。 最后,要解析数据,请使用以下行:

var data = JsonConvert.DeserializeObject<DataModel>(jsonString);

答案 1 :(得分:1)

将此用作模型

using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class JsonModel
    {
        [JsonProperty("featured")]
        public Featured Featured { get; set; }

        [JsonProperty("categories")]
        public List<Category> Categories { get; set; }
    }

    public partial class Category
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("description")]
        public object Description { get; set; }

        [JsonProperty("position")]
        public long Position { get; set; }

        [JsonProperty("media")]
        public List<Featured> Media { get; set; }
    }

    public partial class Featured
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("short_description")]
        public string ShortDescription { get; set; }

        [JsonProperty("rating_avg")]
        public long RatingAvg { get; set; }

        [JsonProperty("image")]
        public string Image { get; set; }

        [JsonProperty("category_media", NullValueHandling = NullValueHandling.Ignore)]
        public CategoryMedia CategoryMedia { get; set; }
    }

    public partial class CategoryMedia
    {
        [JsonProperty("position")]
        public long Position { get; set; }

        [JsonProperty("category_id")]
        public long CategoryId { get; set; }

        [JsonProperty("media_id")]
        public long MediaId { get; set; }

        [JsonProperty("id")]
        public long Id { get; set; }
    }
}

然后在您的课堂上这样做:

var info = JsonConvert.DeserializeObject<JsonModel>(json);
var featured = info.Featured;
var categories = info.Categories;

答案 2 :(得分:0)

请按照以下步骤操作: 使用以下方法更新模型:

public class Category
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public List<Media> Media { get; set; }
}

public class Media
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string ShortDescription { get; set; }
    public string Image { get; set; }
}

public class Featured
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Short_Description { get; set; }
}

然后建立与您的JSON结构相同的模型:

public class YOUR_MODEL
{
      public Featured Featured { get; set; }
      public List<Category> Categories { get;set; }
}

然后将Descrilize JSON移至对象:

YOUR_MODELresults = JsonConvert.DeserializeObject<YOUR_MODEL>(YOUR_JSON);

答案 3 :(得分:0)

Newtonsoft是执行此类工作的标准。因此,让我们看看执行此操作的最佳方法。首先,让我们从json格式开始并进行修复,以便可以使用可用的在线工具来创建良好的模型结构:

[
  {
    "featured": {
      "id": 15,
      "title": "media 1 -> 7",
      "description": "test1",
      "short_description": "test1",
      "rating_avg": 0.0,
      "image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
    },
      "categories": [
        {
          "id": 1,
          "title": "category 0",
          "description": null,
          "position": 0,
          "media": [
            {
              "id": 1,
              "title": "media 0 -> 0",
              "description": "test1",
              "short_description": "test1",
              "rating_avg": 0.0,
              "image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
              "category_media": {
                "position": 0,
                "category_id": 1,
                "media_id": 1,
                "id": 1
              }
            }
          ]
        }
      ]  
  }
]

现在,如果将其插入http://json2csharp.com/,它将输出一个好的模型结构:

public class Featured
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string short_description { get; set; }
    public double rating_avg { get; set; }
    public string image { get; set; }
}

public class CategoryMedia
{
    public int position { get; set; }
    public int category_id { get; set; }
    public int media_id { get; set; }
    public int id { get; set; }
}

public class Medium
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string short_description { get; set; }
    public double rating_avg { get; set; }
    public string image { get; set; }
    public CategoryMedia category_media { get; set; }
}

public class Category
{
    public int id { get; set; }
    public string title { get; set; }
    public object description { get; set; }
    public int position { get; set; }
    public List<Medium> media { get; set; }
}

public class RootObject
{
    public Featured featured { get; set; }
    public List<Category> categories { get; set; }
}

随意重命名RootObject,现在让我们看一下如何使用Newtonsoft将json反序列化为模型对象:

首先,您需要将json文件转换为字符串格式,因此,可以说它是您计算机上或项目中的文件,可以使用Assembly或{{1 }} 方法。一旦可以访问json文件,请先读出内容,然后使用Newtonsoft方法进行反序列化:

Directory

就这样:P

答案 4 :(得分:0)

要获取模型,您可以使用以下工具: https://jsonutils.com/http://json2csharp.com/

如果需要,您还可以使用https://jsonlint.com/来验证json语法,以获取详细的错误。

对您的示例进行稍加修改后,我得到:

public class CategoryMedia
{
    public int position { get; set; }
    public int category_id { get; set; }
    public int media_id { get; set; }
    public int id { get; set; }
}

public class Medium
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string short_description { get; set; }
    public double rating_avg { get; set; }
    public string image { get; set; }
    public CategoryMedia category_media { get; set; }
}

public class Category
{
    public int id { get; set; }
    public string title { get; set; }
    public object description { get; set; }
    public int position { get; set; }
    public IList<Medium> media { get; set; }
}

public class Featured
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string short_description { get; set; }
    public double rating_avg { get; set; }
    public string image { get; set; }
    public IList<Category> categories { get; set; }
}

public class Example
{
    public Featured featured { get; set; }
}

这会浪费大量时间来创建模型,并且使您可以验证字段名称中没有错字。

有了这个,您只需使用选择的库将JSON示例反序列化为“ Example”类。 Newtonsoft Json是非常有效的经典!