反序列化JSON在Asp.Net MVC控制器对象 [英] Deserialize JSON Objects in Asp.Net MVC Controller

查看:379
本文介绍了反序列化JSON在Asp.Net MVC控制器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化这是由LinqToSql产生的对象。用户可以编辑在视图中的对象的数据,然后它被回发到控制器。编辑的数据来自于JSON。请问这个动作有什么样子的?

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?

喜欢的东西...

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

有没有我缺少的框架一个很好的帮助的静态类?还是我必须创建一个DataContract?

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

非常感谢

推荐答案

<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">System.Web.Script.Serialization.JavaScriptSerializer

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

编辑:糟糕!刚才注意到你传递一个对象而不是字符串....所以你需要使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx\">System.Runtime.Serialization.Json.DataContractJsonSerializer:

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

这篇关于反序列化JSON在Asp.Net MVC控制器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆