I've read two other posts regarding the deserialization error, but I've not gotten anywhere so I'm posting my own question.
I have a WCF service that's returning JSON. Upon deserialization of a specific type, it fails.
In an effort to allow you to easily replicate the error, I've hardcoded the JSON below along with the call.
Essentially you should be able to copy/paste the code below and see it fail.
The consumer needs to deserialize this into a working object. s.Deserialize fails with the error message noted in the Title.
NOTE: I realize there are slashes in my JSON. Those are there for convenience to escape the quotes. Thanks.
Example code:
var s = new JavaScriptSerializer();
var jstr =
"[{\"UserId\":1,\"WorkoutId\":1,\"WorkoutInfo\":[\"Step 1\",\"Step 2\"]},{\"UserId\":2,\"WorkoutId\":2,\"WorkoutInfo\":[\"Step 1a\",\"Step 2a\"]},{\"UserId\":5,\"WorkoutId\":0,\"WorkoutInfo\":[\"new work1\",\"new work 1\",\"new work 1\"]}]";
Workout blah = s.Deserialize<Workout>(jstr);
var response = ServicePOST<Workout>("AddUserWorkout", workout);
and Workout class:
public class Workout
{
public int UserId { get; set; }
public List<string> WorkoutInfo { get; set; }
}
The problem is that you're telling the serializer that it's just a single Workout
, not a list/array of them. This works:
var blah = s.Deserialize<List<Workout>>(jstr);
This isn't directly related to your question, but if at all possible, I'd recommend that you use Json.NET instead of JavaScriptSerializer
.