Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON Objects in Asp.Net MVC Controller

I'm trying to deserialize an object which was generated by LinqToSql. The user is allowed to edit the data of the object in the view and then it gets posted back to the controller. The edited Data comes in JSON. How does this action have to look like?

Something like...

public ActionResult(JsonObject json)
{
    MyClass c = Jsonify(json) as MyClass;
}

Is there a nice helpful static class in the framework I'm missing? Or do I have to create a DataContract?

Many thanks

like image 573
Dänu Avatar asked Jun 01 '10 16:06

Dänu


People also ask

How do I deserialize a JSON object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is serialization in MVC?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.

What is serialization and deserialization in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


1 Answers

System.Web.Script.Serialization.JavaScriptSerializer

public ActionResult Blah(JsonObject json)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var c = js.Deserialize<MyClass>(json);
    return View(c);
}

EDIT: Oops...just noticed you are passing an object instead of string....so you will need to use System.Runtime.Serialization.Json.DataContractJsonSerializer:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass c = (MyClass)serializer.ReadObject(json);
like image 179
Bradley Mountford Avatar answered Sep 30 '22 14:09

Bradley Mountford