Coder Perfect

What is the best way to convert a JSON object to a custom C# object?

Problem

Is there a simple method to populate my C# object with the JSON object that was provided in over AJAX?

This is the JSON Object that JSON.stringify supplied to C# WEBMETHOD from the page.

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

The JSON Object is received by a C# WebMethod.

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

}

The object structure of the JSON Object provided into the WebMethod is represented by a C# class.

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

Asked by MHop

Solution #1

Because we all enjoy one-liners,

Newtonsoft is faster than the default Java script serializer… this one relies on the Newtonsoft NuGet package, which is widely used and superior to the default serializer.

If we have a class, we should utilize the following.

Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);

If there isn’t a class, use dynamic.

var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);

Answered by MSTdev

Solution #2

JSON.NET is a nice approach to use JSON in C#.

JSON.NET – Official Site provides Quick Starts and API Documentation to assist you in working with it.

Here’s an example of how to put it to use:

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

Answered by AndreyAkinshin

Solution #3

If you’re using.NET 3.5 or later, here’s a wrapped up example you can use directly from the framework using Generics to keep your options open. If it’s not only simple objects, you should actually use JSON.net, as others have said.

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

You’ll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Answered by Jammin

Solution #4

You shouldn’t need to do anything extra based on your code sample.

If you send that JSON string to your web method, it will automatically process it and return a populated User object as the SaveTeam method’s parameter.

In general, you can use the JavascriptSerializer class as shown below, or for greater flexibility, utilize one of the many Json frameworks available (Jayrock JSON is an excellent one).

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

Answered by womp

Solution #5

Another very simple solution is to use the Newtonsoft library. Json:

User user = JsonConvert.DeserializeObject<User>(jsonString);

Answered by Daniel

Post is based on https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object