Is there an easy way to populate my C# Object with the JSON object passed via AJAX?
//This is the JSON Object passed to C# WEBMETHOD from the page using JSON.stringify
{
"user": {
"name": "asdf",
"teamname": "b",
"email": "c",
"players": ["1", "2"]
}
}
//C# WebMetod That receives the JSON Object
[WebMethod]
public static void SaveTeam(Object user)
{
}
//C# Class that represents the object structure of JSON Object passed in to the WebMethod
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.
https://github.com/ServiceStack/ServiceStack.Text
ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/
Rather than sending as just an object .
Create a public class of properties that is accessible and send the data to the Webmethod.
use same parameters names in ajax call to send data.
More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html
About
DataContractJsonSerializer Class
you can read here.The following 2 examples make use of either
Example 1: using System.Web.Script.Serialization
Usage: JSON object to Custom C# object
Example 2: using System.Web.Helpers
Usage: JSON object to Custom C# object
This code requires adding System.Web.Helpers namespace found in,
Or
Hope this helps!
To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.
You'll need:
Using JavaScriptSerializer() is less strict than the generic solution offered : public static T Deserialize(string json)
That might come handy when passing json to the server that does not match exactly the Object definition you are trying to convert to.