2

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

}

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!
}

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.

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.

How would the collective SO hivemind consider tackling this problem?

ChadT
  • 7,598
  • 2
  • 40
  • 57

2 Answers2

1

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

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

Dan
  • 12,808
  • 7
  • 45
  • 54
1

I would just do an ajax form post. It's much easier.

http://plugins.jquery.com/project/form

http://malsup.com/jquery/form/

Jonathan Parker
  • 6,705
  • 3
  • 43
  • 54