views:

797

answers:

4

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; }

  }
+4  A: 

Good way to use JSON in C# is JSON.NET

Quick Starts & API Documentation from JSON.NET - Official site help you work with it.

Sample of use it:

    public class User {
        public User(string json) {
            JObject jObject = JObject.Parse(json);
            JToken jUser = jObject["user"];
            name = (string) jUser["name"];
            teamname = (string) jUser["teamname"];
            email = (string) jUser["email"];
            players = jUser["players"].ToArray();
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }
    // Use
    private void Run() {
        string json = @"{""user"":{""name"":""asdf"",
             ""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
        User user = new User(json);
        Console.WriteLine("Name : " + user.name);
        Console.WriteLine("Teamname : " + user.teamname);
        Console.WriteLine("Email : " + user.email);
        Console.WriteLine("Players:");
        foreach (var player in user.players)
            Console.WriteLine(player);
     }
DreamWalker
A very good way. +1
kenny
A: 

Given your code sample, you shouldn't need to do anything else.

If you pass that JSON string to your web method, it will automatically parse the JSON string and create a populated User object as the parameter for your SaveTeam method.

Generally though, you can use the JavascriptSerializer class as below, or for more flexibility, use any of the various Json frameworks out there (Jayrock JSON is a good one) for easy JSON manipulation.

 JavaScriptSerializer jss= new JavaScriptSerializer();
 User user = jss.Deserialize<User>(jsonResponse); 
womp
A: 

JSON.Net is your best bet but, depending on the shape of the objects and whether there are circular dependencies, you could use JavaScriptSerializer or DataContractSerializer.

Sky Sanders
+2  A: 

To keep your options open, if your 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 its not just simple objects you should really use JSON.net.

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

Youll need:

using System.Runtime.Serialization; using System.Runtime.Serialization.Json;

Jammin