javascript - Having trouble deserializing a json array to a c# list -


there many json serializing/deserializing options, i'm not sure 1 correct 1 use, , why there many options seemingly same thing. i've seen jsonconvert, jsonserializer, javascriptserializer, , several others.

looking on correctly deserializng json array c# list of complex objects.

jquery:

 var users = [];     (var = 0; < 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; }     } 

try 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 setting userlist in json ul asign directly data without wrapping on userlist again, set contenttype content-type: 'application/json; charset=utf-8' in ajax settings.

also in action use:

    public actionresult addusers(list<user> userlist)     {      //no need javascriptserializer  

Comments