Reputation: 2444
I am attempting to deserialize a JSON string to an object.
The exception being thrown is:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'APIServer.Models.UserProfileModel'.
This is the JSON string:
"id": "b483c490-8d5a-4247-b3d3-8eb7cc4208bd",
"firstName": "Jeremy",
"lastName": "Krasin",
"gender": null,
"birthDate": null,
"homeCountry": null,
"publicName": null,
"self": {
"href": "http://localhost:54253/api/userprofiles/b483c490-8d5a-4247-b3d3-8eb7cc4208bd",
"relations": [
"collections"
],
"method": "GET",
"routeName": null,
"routeValues": null
},
"href": "http://localhost:54253/api/userprofiles/b483c490-8d5a-4247-b3d3-8eb7cc4208bd",
"relations": [
"collections"
],
"method": "GET",
"routeName": null,
"routeValues": null
This is the class I am trying to deserialize into:
public class UserProfileModel : BaseModel<UserProfileModel> {
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string BirthDate { get; set; }
public string HomeCountry { get; set; }
public string PublicName { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
This is the line of code that is attempting the deserialization:
return (T) JsonConvert.DeserializeObject(RestClient.Execute(aRequest).Content);
I verified that T
is the following type:
APIServer.Models.UserProfileModel
What am I doing wrong?
Upvotes: 0
Views: 129
Reputation: 129657
You need to specify the type when you call DeserializeObject
like this:
return JsonConvert.DeserializeObject<T>(RestClient.Execute(aRequest).Content);
^^^
When you do not specify the type, DeserializeObject
will return a JObject
, which cannot be cast to your APIServer.Models.UserProfileModel
. This is why you are getting an error.
Upvotes: 2