Thursday, 5 September 2013

How to capture JSON array and single object?

How to capture JSON array and single object?

I have an ActionResult method that accepts as an argument:
public ActionResult MyMethod (List<ClassA> json)
{
...
}
This binds the json string coming in to the a generic list of ClassA
objects, which are populated.
The problem is sometimes the json coming in is just a single json object
and not an array of json objects.
Is there some way to preempt this so I can bind directly to ClassA vs
List? Or is there some other technique I can use?
Here is how the JSON is being sent (as an array):
var myjsonarray = [{
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
}, {
"ID": "2",
"FirstName": "Jane",
"LastName": "Doe",
}];
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/MyPage",
data: JSON.stringify(myjsonarray),
dataType: 'json'
});
The above processes fine. This also works:
var myjsonarray = [{
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
}];
But when I send as a single object not wrapped in an array:
var myjsonarray = {
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
};
My ActionResult method parameter is null:
json == null

No comments:

Post a Comment