6

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

1 Answer 1

23

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);
Sign up to request clarification or add additional context in comments.

4 Comments

nice, thanks (and yeeess maybe I was a little to lazy to rtfm ;-))
Seems to me the DataContractJsonSerializer's ReadObject method only accepts XML readers or streams as input?
What would be the .NET 5 approach to this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.