I am trying to deserialize a Json object that I am getting from the LinkedIn Javascript API:
{"_key":"~","educations":{"_total":2,"values":[{"degree":"Bachelor of Science (BSc)","endDate":{"year":2004},
"fieldOfStudy":"Computer Software Engineering","id":134450447,"schoolName":"Bristol University","
startDate":{"year":2009}},{"id":143651018,"schoolName":"University of Kingston"}]},"emailAddress":
"test@test.com","firstName":"Robert","lastName":"Matthews"}
I have written a custom class to store these values and deserialize them using Json.NET:
[Serializable]
public class LinkedInUserData {
[JsonProperty(PropertyName = "emailAddress")]
public string EmailAddress { get; set; }
// other properties cut out for simplicity
[JsonProperty(PropertyName = "educations")]
public Educations Educations { get; set; }
}
[Serializable]
public class Educations {
[JsonProperty(PropertyName = "_total")]
public string Total { get; set; }
[JsonProperty(PropertyName = "values")]
public Values Values { get; set; }
}
[Serializable]
public class Values { // cut down for simplicity
[JsonProperty(PropertyName = "degree")]
public string Degree { get; set; }
}
LinkedInUserData linkedData = JsonConvert.DeserializeObject<LinkedInUserData>(profile);
I am able to convert the single objects (no array, etc.) without any problem but I am getting stuck on the Values object in Educations, with the following error message:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
‘Data.Values’ 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
‘educations.values’, line 1, position 47.
I have tried changing the Values object in Educations to a string array but with no luck. Is there any way to successfully deserialize the values from the Json into my custom class or is it only possible to get something along the lines of a string array?
Edit – List (of values) products the following error:
Error reading string. Unexpected token: StartObject. Path
‘educations.values[0].endDate’, line 1, position 96.
Edit 2 – Ok I get it now, List (of values) did work, and then it was tripping up on StartDate and EndDate because these are objects in themselves, and I has these both set as strings. I was struggling to make sense of the Json string but Link2CSharp helped me to solve it.
I believe you need to restructure your class against the json. You can try generating C# classes against the Json using json2csharp (A very good resource if you want to automatically create C# classes against the json). Following is the structure it gives. You can use that with JSON.Net to get the object.