Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've found it really handy that in MVC3 ASP.NET will map the incoming JSON request body to a simple specified object in the form of an argument...

Is there any way to utilize this functionality outside that specific use case?

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

like image 725
jondavidjohn Avatar asked Nov 14 '11 15:11

jondavidjohn


People also ask

Can a JSON object be a string?

JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format. When it is converted to a JavaScript variable, it becomes a JavaScript object.

Which method converts a JSON string to a JavaScript object?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

How do you represent a dictionary in JSON?

Introducing JSON JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .

How do you convert a string to a JSON object in Python?

To convert string to json in Python, use the json. loads() function. The json. loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements.


1 Answers

Sure, you could use a JSON serializer such as the JavaScriptSerializer class which is what ASP.NET MVC uses or a third party library such as Json.NET. For example:

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);
    }
}
like image 199
Darin Dimitrov Avatar answered Sep 30 '22 11:09

Darin Dimitrov