绑定应用程序/ JSON来POCO对象asp.net的MVC,序列化异常 [英] Binding application/json to POCO object in asp.net mvc, Serialization exception

查看:68
本文介绍了绑定应用程序/ JSON来POCO对象asp.net的MVC,序列化异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递回JSON从我的观点我的控制器动作来执行操作。要转换在发送的JSON,到POCO我用这个动作过滤器:

I'm passing json back up from my view to my controller actions to perform operations. To convert the json being sent in, to a POCO I'm using this Action Filter:

public class ObjectFilter : ActionFilterAttribute {
public Type RootType { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext) {
IList<ErrorInfo> errors = new List<ErrorInfo>();
try {
    object o = new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
    filterContext.ActionParameters["postdata"] = o;
    }
catch (SerializationException ex) {
    errors.Add(new ErrorInfo(null, ex.Message));
}
finally {
    filterContext.ActionParameters["errors"] = errors.AsEnumerable();
}

}

这是使用DataContractJsonSerializer映射的JSON,到我的对象。我的行动是再点缀,像这样:

It's using the DataContractJsonSerializer to map the JSON, over to my object. My Action is then decorated like so:

[ObjectFilter(RootType = typeof(MyObject))]
public JsonResult updateproduct(MyObject postdata, IEnumerable<ErrorInfo> errors) {
    // check if errors has any in the collection!
}

所以要猜测,什么是怎么回事,如果有序列化JSON到对象的类型(如字符串不能被解析为十进制类型或如类似的)一个问题,它增加了错误的集合然后再将这个错误直到视图。然后,它可以检查,如果此集合有一个错误,并报告给客户端。

So to surmise, what is going on here, if there is a problem serializing the JSON to the type of object (if a string cannot be parsed as a decimal type or similar for eg), it adds the error to a collection and then passes that error up to the view. It can then check if this collection has an errors and report back to the client.

问题是,我似乎无法找出的字段造成的问题。理想情况下,我想回传给视图,并说:这个领域出现了问题。该SerializationException类似乎没有提供这种灵活性。

The issue is that I cannot seem to find out which field has caused the problem. Ideally I'd like to pass back to the view and say "THIS FIELD" had a problem. The SerializationException class does not seem to offer this sort of flexibility.

如何将集体SO HiveMind的考虑解决这个问题?

How would the collective SO hivemind consider tackling this problem?

推荐答案

这个怎么样: Json.Net
它读取一个JSON字符串,然后将其Deserialises给定的POCO对象。

How about this: Json.Net It reads a JSON string and then Deserialises it to the given POCO object.

string jsonResult = GetJsonStringFromSomeService();
MyPocoObject myobject = JsonConvert.DeserializeObject<MyPocoObject>(jsonResult);
Console.Write("Damn that is easy");

但对于那些出现错误的determing,我也不太清楚。

But for the determing where errors occur, I am not too sure.

这篇关于绑定应用程序/ JSON来POCO对象asp.net的MVC,序列化异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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