将多级JSON对象数组反序列化为C#类

时间:2016-02-13 15:24:07

标签: json c#-4.0 serialization

我是JSON的新手,很难从API反序列化JSON Feed。我使用Newtonsoft的JSON.NET。下面的JSON显示了包含媒体的产品。我可以访问产品信息,ID,cnk,名称等...没有问题。但问题在于媒体结构。媒体包含名称为" 450x450"和" 900x900"。在每种类型中,可以有一个,多个对象,甚至没有。

JSON Feed:

`

{
"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);

            }

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

感谢,

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。在对象中寻址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());
}

}

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

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]

我在这个论坛的某处发现了这个声明。但它没有做我想要的。我对此进行了评论,我可以访问我的数据!

的问候,