【问题标题】:Deserialize multi level JSON Array of objects to C# classes将对象的多级 JSON 数组反序列化为 C# 类
【发布时间】:2016-02-13 15:24:07
【问题描述】:

我是 JSON 新手,在从 API 反序列化 JSON 提要时遇到困难。我使用来自 Newtonsoft 的 JSON.NET。下面的 JSON 也显示了包含媒体的产品。我可以毫无问题地访问产品信息、id、cnk、名称等。但问题在于媒体结构。媒体包含名称为“450x450”和“900x900”的数组。每种类型都可以有一个、多个对象,甚至没有。

JSON 提要:

`

{
"products" : [
    {
      "id": 44649,
      "cnk": "2753982",
      "language": "nl",
      "last_updated_at": "2015-12-10T15:19:51+0000",
      "status": "active",
      "name": "EUCERIN tube",
      "febelco_name": "EUCERIN tube 2",
      "ean": "4005000019875",
      "apb_category": "cosmetics",
      "weight": 62,
      "width": 38,
      "height": 126,
      "depth": 49,
      "prescription": false,
      "tax": 21,
      "public_price_apb": 7.8,
      "public_price_febelco": 12.9,

      "media": {
        "450x450": [
          {
            "id": 26587,
            "path": "media\/450x450\/19e09206ae752105101d2235935959ab4b085869.jpg",
            "file_path": "media\/450x450\/19e09206ae752105101d2235935959ab4b085869.jpg",
            "image_type": "packshot",
            "last_updated_at": "2015-11-16T00:00:00+0000"
          }
        ],
        "900x900": [
          {
            "id": 26587,
            "path": "media\/900x900\/f24fb9a2c308ff091addf6c3f744850004962d6f.jpg",
            "file_path": "media\/900x900\/f24fb9a2c308ff091addf6c3f744850004962d6f.jpg",
            "image_type": "packshot",
            "last_updated_at": "2015-11-16T00:00:00+0000"
          }
        ]
      }
    }
    ]

} 

`

我使用的是VS2013,我使用了自定义类创建功能:

EDIT -> Paste Special -> Paste JSON as Classes

这提供了以下类:

public class MediProduct
{
    public int id { get; set; }
    public string cnk { get; set; }
    public string language { get; set; }
    public DateTime last_updated_at { get; set; }
    public string status { get; set; }
    public string name { get; set; }
    public string ean { get; set; }
    public string apb_category { get; set; }
    public bool prescription { get; set; }
    public int tax { get; set; }
    public float public_price_apb { get; set; }
    public float public_price_febelco { get; set; }
    public Consumer_Categories[] consumer_categories { get; set; }
    public Media media { get; set; }
    public string febelco_name { get; set; }
    public int weight { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public int depth { get; set; }
    public string description { get; set; }
    }

public class Media
{
 [JsonProperty(PropertyName = "450x450")]
public _450X450[] _450x450 { get; set; }
public _900X900[] _900x900 { get; set; }
}

public class _450X450
{
public int id { get; set; }
public string path { get; set; }
public string file_path { get; set; }
public string image_type { get; set; }
public DateTime last_updated_at { get; set; }
}

public class _900X900
{
public int id { get; set; }
public string path { get; set; }
public string file_path { get; set; }
public string image_type { get; set; }
public DateTime last_updated_at { get; set; }
}

所以我必须获得“媒体”项目,其中可以有多个“450x450”对象,其中包含我想要的数据。我不知道如何达到这个水平,尤其是如何摆脱object reference is not set to an instance of an object 错误。我尝试了以下方法:

`

 //Get JSON result objects into a list
            IList<JToken> results = PartProduct["products"].Children().ToList();

            //serialize JSON results into .net objects

            //IList<UsefulProduct> ReturnProducts = new List<UsefulProduct>();
            IList<MediProduct> ReturnProducts = new List<MediProduct>();




            //add the different products to the list
            foreach (JToken result in results)
            {
                //UsefulProduct usefulProduct = JsonConvert.DeserializeObject<UsefulProduct>(result.ToString()); 
                MediProduct MyProduct = JsonConvert.DeserializeObject<MediProduct>(result.ToString());
                if (null == result["description"])
                {
                    MyProduct.description  = "/";
                }


                    dynamic Rommel = JsonConvert.DeserializeObject<_450X450[]>(result["450x450"].ToString());
                    //Console.WriteLine(StommeFoto._450x450.id);  



                ReturnProducts.Add(MyProduct);

            }

但是我无法访问媒体对象中的数据。请帮忙!

谢谢,

【问题讨论】:

    标签: json c#-4.0 serialization


    【解决方案1】:

    我发现了问题。在对象中寻址 Json 对象时,如下代码所示:

        "media": {
                "450x450": [
                  {
                    "id": 26587,
                    "path": "media\/450x450\/19e09206ae752105101d2242935959ab4b074869.jpg",
                    "file_path": "media\/450x450\/19e09206ae752105101d2242935959ab4b074869.jpg",
                    "image_type": "packshot",
                    "last_updated_at": "2015-11-16T00:00:00+0000"
                  }
                ],
                "900x900": [
                  {
                    "id": 26587,
                    "path": "media\/900x900\/f24fb9a2c308ff091adbc6c3f744850005962d6f.jpg",
                    "file_path": "media\/900x900\/f24fb9a2c308ff091adbc6c3f744850005962d6f.jpg",
                    "image_type": "packshot",
                    "last_updated_at": "2015-11-16T00:00:00+0000"
                  }
                ]
              }
    

    有一个“媒体”对象包含 2 个数组,一个类型为“450x450”,另一个类型为“900x900”。因此,要处理这些数据,您必须处理正确的子对象。

      //Get JSON result objects into a list
                IList<JToken> results = PartProduct["products"].Children().ToList();
    
                //serialize JSON results into .net objects
    
                //IList<UsefulProduct> ReturnProducts = new List<UsefulProduct>();
                IList<MediProduct> ReturnProducts = new List<MediProduct>();
    
    
    
    
                //add the different products to the list
                foreach (JToken result in results)
                {
    
                    MediProduct MyProduct = new MediProduct();
                    MyProduct = JsonConvert.DeserializeObject<MediProduct>(result.ToString());
                    if (null == result["description"])
                    {
                        MyProduct.description = "/";
                    }
    
                    if (null != result["media"]["450x450"])
                    {
                        //to get the picture array. You have to address the correct path, in this case ["media"] "[450x450]
                        _450X450[] Foto450x450 = JsonConvert.DeserializeObject<_450X450[]>(result["media"]["450x450"].ToString());
                        _900X900[] Foto900x900 = JsonConvert.DeserializeObject<_900X900[]>(result["media"]["900x900"].ToString());
    }
    
    }
    

    通过在 result["media"]["450x450"] 子集中搜索,我能够在正确的数组中获取数据。 我还发现,在我的类定义中,以下语句阻止了数据:

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]

    我在这个论坛的某个地方找到了这个声明。但它没有做我想要的。我将其注释掉,我可以访问我的数据!

    问候,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多