将JSON对象转换为对象列表C#

时间:2015-08-12 12:48:59

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

我有一个将JSON对象转换为特定列表的web api服务:

这是模型类:

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 List<rest_all_data> rest_all_data { get; set; }
} 

这是服务:

public void AddRestaurantMultiple([FromBody] JObject rest_all)
{
    string k = rest_all.ToString();
    rest_collection result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<rest_collection>(k); 
}

这里是json对象:

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

rest_all对象始终带有数据,k字符串也是成功的,但result变量始终为空...

2 个答案:

答案 0 :(得分:1)

试试我在您的代码中进行了一些更改

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

    public void AddRestaurantMultiple([FromBody] JObject rest_all)
    {
        string k = rest_all.ToString();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        rest_collection collection = serializer.Deserialize<rest_collection>(k);
    }

答案 1 :(得分:0)

尝试:

public void AddRestaurantMultiple([FromBody] string rest_all)
{
    var obj = JsonConvert.DeserializeObject<rest_collection>(rest_all);
}