简体   繁体   中英

convert json string to c# list of objects (string comes from request as NULL)

I have the following code to convert json string to list of objects:

        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; }
        }

and here is the main function:

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

the problem is that when I make an http request with a json string like this:

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

it always gives me null at the AddRestaurantMultiple function...what is it am i doing wrong??

Your model should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM