Search code examples
c#asp.net.netajaxjson

How can I convert a JSON object to a custom C# object?


How can I populate my C# object with the JSON object passed via AJAX?

This is the JSON object passed to a C# web method from the page using JSON.stringify:

{
    "user": {
        "name": "asdf",
        "teamname": "b",
        "email": "c",
        "players": ["1", "2"]
    }
}

The C# web method that receives the JSON object:

[WebMethod]
public static void SaveTeam(Object user)
{

}

The C# class that represents the object structure of JSON Object passed in to the web method

public class User
{
    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

Solution

  • A good way to use JSON in C# is with JSON.NET

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

    An example of how to 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);
     }