views:

253

answers:

3

How can I de-serialize a json object sent from javascript (using jquery.ajax) to a .aspx page (not a web service)?

e.g. if I have the following json object;

var json = {"name" : "michael", "surname" : "brown", "age" : "35"}

and I use

$.post('process.aspx', json)

how do I get to deserialize the json in process.aspx code behind?

also, how do I use the $.postJSON() in my case?

+3  A: 

You can use the DataContractJsonSerializer built into .Net 3.5, or there's a great open source Json library that we use: http://jayrock.berlios.de/

To use the DataContractJsonSerializer, your code might look something like this:

var serializer = new DataContractJsonSerializer(typeof(Person));
using (MemoryStream ms = new MemoryStream(new ASCIIEncoding().GetBytes(myString)))
{
  try
  {
    Person obj = serializer.ReadObject(ms) as Person;
  }
  catch (Exception e)
  {
    throw new InvalidOperationException("Could not deserialize Person.", e);
  }
}
womp
+1  A: 

The NewtonSoft library is a good option.

redsquare
+1  A: 

You could use DataContractJsonSerializer:

class Program
{
    [DataContract]
    class Person
    {
        [DataMember(Name = "name")]
        public string Name { get; set; }
        [DataMember(Name = "surname")]
        public string Surname { get; set; }
        [DataMember(Name="age")]
        public int Age { get; set; }
    }

    static void Main(string[] args)
    {
        var json = @"{""name"" : ""michael"", ""surname"" : ""brown"", ""age"" : ""35""}";

        var serializer = new DataContractJsonSerializer(typeof(Person));
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            var person = (Person)serializer.ReadObject(stream);
            Console.WriteLine("Name : {0}, Surname : {1}, Age : {2}", 
                person.Name, person.Surname, person.Age);
        }
    }
}
Darin Dimitrov