Json反序列化失败

时间:2020-03-28 20:37:07

标签: c# json json.net deserialization

我正在尝试将JSON字符串反序列化为对象。

抛出的异常是:

无法将类型为“ Newtonsoft.Json.Linq.JObject”的对象转换为类型为“ APIServer.Models.UserProfileModel”。

这是JSON字符串:

"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

这是我要反序列化的课程:

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; }
}

这是尝试反序列化的代码行:

return (T) JsonConvert.DeserializeObject(RestClient.Execute(aRequest).Content);

我验证了T是以下类型:

APIServer.Models.UserProfileModel

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

像这样呼叫DeserializeObject时需要指定类型:

return JsonConvert.DeserializeObject<T>(RestClient.Execute(aRequest).Content);
                                    ^^^

当您不指定类型时,DeserializeObject将返回JObject,该类型不能转换为您的APIServer.Models.UserProfileModel。这就是为什么您会遇到错误。

相关问题