如何对包含实体列表以及其他属性的json进行去别化

时间:2012-03-13 05:49:22

标签: c# asp.net-mvc-3

我有一个包含MyFacebookClass列表的json,当我反序列化MyFacebookClass列表时,我得到的错误是没有空白构造函数为CustomObject定义,虽然我已经定义了构造函数,如下所示,所以请帮帮我。

    public class MyFacebookClass
    {
    public MyFacebookClass
    {
      data =new List<CustomObject>();
    }
        public string Name{get;set;}
        public int Id{get;set;}
        public List<CustomObject> data {get;set;}
    }

    public class CustomObject 
    {
    public CustomObject()
    {
    }
      public string id {get;set;}
      public string name {get;set;}
    }

我正在使用:

    List<MyFacebookClass> routes_list = new List<MyFacebookClass>();
    JavaScriptSerializer jSerializer = new JavaScriptSerializer();
    routes_list = jSerializer.Deserialize<List<MyFacebookClass>>(json);

2 个答案:

答案 0 :(得分:0)

您在已发布的代码中没有CustomObject的构造函数。基本上,构造函数是一个没有返回类型且与声明类同名的方法。你有MyFacebookClass here is the MSDN documentation on constructors.

的构造函数
public class CustomObject 
{
  public CustomObject()
  {
    /*  now you have a constructor */
  }
  public string id {get;set;}
  public string name {get;set;}
}

答案 1 :(得分:0)

工作完美。只有我在你的代码中找到的问题是,MyFacebookClass类构造函数应该有括号

public class MyFacebookClass
{
    public MyFacebookClass()
    {
        data = new List<CustomObject>();
    }

    public string Name { get; set; }
    public int Id { get; set; }
    public List<CustomObject> data { get; set; }
}

public class CustomObject
{
    public CustomObject()
    {
        /*  now you have a constructor */
    }
    public string id { get; set; }
    public string name { get; set; }
}

public class Main
{
    public List<MyFacebookClass> Deserialize(string json)
    {
        List<MyFacebookClass> routes_list = new List<MyFacebookClass>();
        JavaScriptSerializer jSerializer = new JavaScriptSerializer();
        return jSerializer.Deserialize<List<MyFacebookClass>>(json); 
    }
}

[TestMethod的()]

    public void doSomethingTest()
    {
        Main target = new Main(); // TODO: Initialize to an appropriate value
        Assert.AreEqual(target.Deserialize(""), null);
    }