How to bind a JSON string to the definition of a real object?

It was very convenient for me that in MVC3 ASP.NET will map the incoming body of the JSON request to a simple given object in the form of an argument ...

Can this functionality be used outside this particular use case?

To do this even further, in standard .NET programming, take a json string and map (bind) it to a real object ... (not a dictionary)?

+5
source share
1 answer

Of course, you can use a JSON serializer such as the JavaScriptSerializer class that uses ASP.NET MVC or a third-party library such as Json.NET . For instance:

using System;
using System.Web.Script.Serialization;

public class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var serializer = new JavaScriptSerializer();
        var json = "{name: 'John', age: 15}";
        var customer = serializer.Deserialize<Customer>(json);
        Console.WriteLine("name: {0}, age: {1}", customer.Name, customer.Age);
    }
}

or with Json.NET if you prefer:

using System;
using Newtonsoft.Json;

public class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var json = "{name: 'John', age: 15}";
        var customer = JsonConvert.DeserializeObject<Customer>(json);
        Console.WriteLine("name: {0}, age: {1}", customer.Name, customer.Age);
    }
}
+11
source

All Articles