I seem to be running into an issue where I try to deserialize a json array into a C# list (I'm using Json.NET). The problem is I'm getting an error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ProjectName.WebServices.EventWebMethods+ServiceItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '[0]', line 1, position 2.
This is my json code which is created by taking a javascript array and using JSON.stringify on it:
[["6249","Locked"],["6250","Locked"],["6251","Locked"]]
This is the C# code I am using:
[Serializable]
public class ServiceItem
{
long lngId{ get; set; }
string strStatus{ get; set; }
public ServiceItem() { }
}
[WebMethod(EnableSession = true)]
public string Create(string strJSON)
{
//Error happens on this next line:
List<ServiceItem> ServiceData = JsonConvert.DeserializeObject<List<ServiceItem>>(strJSON);
return "test";
}
How do I get this to deserialize into the C# class. Any help is appreciated!
UPDATE
I made the changes to my javascript so that it includes the variable names as per suggested. Still same error. Here is the JSON in the C# variable:
[
[\"lngId\" : \"6249\",\"strStatus\" : \"Locked\"],
[\"lngId\" : \"6250\",\"strStatus\" : \"Locked\"],
[\"lngId\" : \"6251\",\"strStatus\" : \"Locked\"]
]
Are the curly braces that important, and if that is the problem, why doesn't JSON.Stringify do that?
UPDATE 2
Figured it out. I needed to create each json item like this:
arrServices.push({"lngId": intServiceID, "strStatus" : "Locked"});
Now it works. Thank you for the help!