【问题标题】:Json deserialization is failingJson 反序列化失败
【发布时间】:2020-03-28 20:37:07
【问题描述】:

我正在尝试将 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

我做错了什么?

【问题讨论】:

    标签: c# json json.net deserialization


    【解决方案1】:

    调用DeserializeObject时需要指定类型,如下:

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

    当你不指定类型时,DeserializeObject 将返回一个JObject,它不能转换为你的APIServer.Models.UserProfileModel。这就是您收到错误的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2023-03-20
      相关资源
      最近更新 更多