将json字符串转换为c#对象列表(字符串来自请求为NULL)

时间:2015-08-11 16:37:37

标签: c# asp.net json web-services

我有以下代码将json字符串转换为对象列表:

        public class rest_all
        {
            public string restaurants { get; set; } 
        }


        public class rest_all_data
        {
            public string RestaurantName { get; set; }
            public string CategoryName { get; set; }
            public string FourSquareID { get; set; } 
        }


        public class rest_collection 
        {
            public IEnumerable<rest_all_data> rest_all_data { get; set; }
        }

这是主要功能:

public void AddRestaurantMultiple (rest_all rest_all)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            rest_collection collection = serializer.Deserialize<rest_collection>(rest_all.restaurants);
        }

问题是当我用这样的json字符串发出http请求时:

{"restaurants" : [{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]

它总是在AddRestaurantMultiple函数给我null ...我做错了什么?

1 个答案:

答案 0 :(得分:4)

你的模特应该是

public class Restaurant
{
    public string RestaurantName { get; set; }
    public string CategoryName { get; set; }
    public string FourSquareID { get; set; }
}

public class rest_collection
{
    public List<Restaurant> restaurants { get; set; }
}
var result = new JavaScriptSerializer().Deserialize<rest_collection>(yourjson);