Prabhu
Prabhu

Reputation: 13325

Having trouble deserializing a json array to a c# list

There are so many json serializing/deserializing options, so I'm not sure which one is the correct one to use, and why there are so many options to do seemingly the same thing. I've seen JsonConvert, JsonSerializer, JavaScriptSerializer, and several others.

Looking for help on correctly deserializng a json array into a c# list of complex objects.

JQUERY:

 var users = [];
    for (var i = 0; i < response.length; i++) 
    {
        var u = 
        {
            Id: response[i].id,
            UserName: response[i].username,
            FirstName: response[i].first_name,
            LastName: response[i].last_name    
        };
        users[i] = u;
    }

    var ul = JSON.stringify({ 'userlist': users});
    $.ajax({
        type: "POST",
        url: "/myurl/addusers",
        data: { 'userlist': ul },
        dataType: "json",
        success: function (response) {  

        },
        error: function (xhr, status, error) {

        }
    });

C# (this doesn't work):

        [HttpPost]
        public ActionResult AddUsers(string userlist)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            var users = ser.Deserialize<List<User>>(userlist); 
            ...
        }  

    [Serializable]
    public class User
    {
        public string Id { get; set; }
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Upvotes: 1

Views: 982

Answers (2)

PSL
PSL

Reputation: 123739

Try this way:

var ul = JSON.stringify({ 'userlist': users});
    $.ajax({
        type: "POST",
        url: "/myurl/addusers",
        data: ul ,
        content-Type: 'application/json; charset=utf-8', 
        dataType: "json",
        success: function (response) {  

        },
        error: function (xhr, status, error) {

        }
    });

You already are setting userlist in the json ul so just asign it directly to data without wrapping it over userlist again, also set the contentType content-Type: 'application/json; charset=utf-8' in the ajax settings.

Also in your action just use:

    public ActionResult AddUsers(List<User> userlist)
    {
     //no need to do JavaScriptSerializer 

Upvotes: 3

Alexandr Mihalciuc
Alexandr Mihalciuc

Reputation: 2577

Change your action to accept List of users, the model binder will take care of the rest, like that:

 [HttpPost]
        public ActionResult AddUsers(List<User> users)
        {
            //use the 
        }

Change javascript to send the users array directly, without surrogate property:

var ul = JSON.stringify(users);
    $.ajax({
        type: "POST",
        url: "/myurl/addusers",
        data: ul ,
        dataType: "json",
        success: function (response) {  

        },
        error: function (xhr, status, error) {

        }
    });

Upvotes: 1

Related Questions