Deserializing JSON objects as List<type> not working with asmx service Deserializing JSON objects as List<type> not working with asmx service asp.net asp.net

Deserializing JSON objects as List<type> not working with asmx service


I figured it out. I wasn't wrapping my JSON in an object like ASP.NET Ajax requires. For future viewers of this question, all JSON objects must be wrapped with a main object before being sent to the web service. The easiest way to do this is to create the object in JavaScript and use something like json2.js to stringify it. Also, if using an asmx web service, the objects must have a __type attribute to be serialized properly. An example of this might be:

var person=new object;person.firstName="chris";person.lastName="Westbrook";person.seq=-1;var data=new object;data.p=person;JSON.stringify(data);

This will create an object called p that will wrap a person object. This can then be linked to a parameter p in the web service. Lists of type person are made similarly, accept using an array of persons instead of just a single object. I hope this helps someone.


Could you show the JSON string you are trying to deserialize and the way you are using the Deserialize method? The following works fine:

using System;using System.Collections.Generic;using System.Web.Script.Serialization;namespace Test{    class Program    {        class Person         {            public int SequenceNumber { get; set; }            public string FirstName { get; set; }            public string LastName { get; set; }        }        public static void Main()         {            string json = "[{\"SequenceNumber\":1,\"FirstName\":\"FN1\",\"LastName\":\"LN1\"},{\"SequenceNumber\":2,\"FirstName\":\"FN2\",\"LastName\":\"LN2\"}]";            IList<Person> persons = new JavaScriptSerializer()                .Deserialize<IList<Person>>(json);            Console.WriteLine(persons.Count);        }    }}


Or even simpler, when you are doing the $.ajax(...) use

data:"{\"key\":"+JSON.stringify(json_array)+"}",

and then on the other side of the code, make your function use the parameter "object key"

[WebMethod]public static return_type myfunction(object key){...}