{
"access_token":"asfdasfdsf",
"token_type":"bearer",
"expires_in":15179999,
"refresh_token":"sdsfsf",
".issued":"Sat, 28 Apr 2018 03:05:12 GMT",
".expires":"Sat, 20 Oct 2018 19:45:12 GMT",
"ip_address":"111.111.11.1",
"client_id":"asdsdfsf",
"user":"{\r\n \"Active\": true,\r\n \"DisplayName\": \"Sakib Hasan\",\r\n \"Email\": \"test@testc.om\",\r\n \"EmailVarified\": true,\r\n \"Language\": \"en-US\",\r\n \"PhoneNumber\": null,\r\n \"ProfileImageUrl\": null,\r\n \"Roles\": [\r\n \"anonymous\",\r\n \"admin\"\r\n ],\r\n \"TenantId\": \"asfsf\",\r\n \"UserName\": \"test@testc.com\",\r\n \"FirstName\": null,\r\n \"UserSignup\": false,\r\n \"ProfileImageId\": null,\r\n \"EverLoggedIn\": true,\r\n \"PersonIdentifier\": null,\r\n \"UserId\": \"sdfsff\"\r\n}",
"may_access":""
}
我正在尝试将上面的字符串反序列化为我的C#对象。我的课程如下所示
internal class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("user")]
public TokenUser User { get; set; }
}
internal class TokenUser
{
[JsonProperty("DisplayName")]
public string DisplayName { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("ProfileImageUrl")]
public string ProfileImageUrl { get; set; }
[JsonProperty("UserName")]
public string UserName { get; set; }
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("UserId")]
public string UserId { get; set; }
}
现在当我尝试使用Newtonsoft
进行反序列化时tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(jsonTokenResponse);
我得到无法将字符串转换为用户错误。我在这里错过了什么吗?
答案 0 :(得分:1)
试试这个,
internal class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("user")]
public string User { get; set; }
[JsonIgnore]
public TokenUser UserToken { get; set; }
}
internal class TokenUser
{
[JsonProperty("DisplayName")]
public string DisplayName { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("ProfileImageUrl")]
public string ProfileImageUrl { get; set; }
[JsonProperty("UserName")]
public string UserName { get; set; }
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("UserId")]
public string UserId { get; set; }
}
tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(jsonTokenResponse);
tokenResponse.UserToken = JsonConvert.DeserializeObject<TokenUser>(tokenResponse);
因为您的用户属性在期望TokenUser时收到字符串
答案 1 :(得分:0)
回答以后的参考。
问题在于Json本身。它将'user'视为一个字符串,并没有转换为User对象。所以我不得不清理它,所以DeSerializer(ds)知道它是一个对象。
json2csharp帮助我找出问题所在。如果你把上面的Json放在里面,它会创建一个带有字符串属性的类。
清理后jsonformatter是一个很好的验证清理版本是否仍然是好的json。