这是使用 Console.Writeline
打印的 Json 字符串:
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLmRydW1zdGlrLmFwcFwvYXBpXC9sb2dpbiIsImlhdCI6MTYwMzgxNTcxMywiZXhwIjoxNjAzODE5MzEzLCJuYmYiOjE2MDM4MTU3MTMsImp0aSI6InJhU1dJSHBJaWR0YnhjTUUiLCJzdWIiOjQ1LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.aaQoQVKTSMFWCEOMv9psVsMeOJqpC5giLfwZ0Uic444","token_type":"bearer","expires_in":3600}
我想构建一个 C# 对象:
public class eltoken
{
[JsonProperty("access_token")]
public string AccesToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public long ExpiresIn { get; set; }
}
eltoken test = JsonConvert.DeserializeObject<eltoken>(response.Content.ReadAsStringAsync().Result.ToString());
//------------
Console.WriteLine(test.AccesToken);
但我不明白为什么它是空的。
最佳答案
您可能没有正确等待。首先,这不是使用异步 API 的正确方法:
eltoken test = JsonConvert.DeserializeObject<eltoken>(response.Content.ReadAsStringAsync().Result.ToString());
尝试一下:
var json = await response.Content.ReadAsStringAsync();
// debug write/inspect json here
eltoken test = JsonConvert.DeserializeObject<eltoken>(json);
从根本上来说,反序列化步骤没问题,所以问题可能是 JSON 不是您想象的那样:
using Newtonsoft.Json;
using System;
class P
{
static void Main()
{
var json = @"{""access_token"":""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLmRydW1zdGlrLmFwcFwvYXBpXC9sb2dpbiIsImlhdCI6MTYwMzgxNTcxMywiZXhwIjoxNjAzODE5MzEzLCJuYmYiOjE2MDM4MTU3MTMsImp0aSI6InJhU1dJSHBJaWR0YnhjTUUiLCJzdWIiOjQ1LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.aaQoQVKTSMFWCEOMv9psVsMeOJqpC5giLfwZ0Uic444"",""token_type"":""bearer"",""expires_in"":3600}";
eltoken test = JsonConvert.DeserializeObject<eltoken>(json);
Console.WriteLine(test.ExpiresIn);
Console.WriteLine(test.TokenType);
Console.WriteLine(test.AccesToken);
}
}
public class eltoken
{
[JsonProperty("access_token")]
public string AccesToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public long ExpiresIn { get; set; }
}
其输出如预期:
3600
bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLmRydW1zdGlrLmFwcFwvYXBpXC9sb2dpbiIsImlhdCI6MTYwMzgxNTcxMywiZXhwIjoxNjAzODE5MzEzLCJuYmYiOjE2MDM4MTU3MTMsImp0aSI6InJhU1dJSHBJaWR0YnhjTUUiLCJzdWIiOjQ1LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.aaQoQVKTSMFWCEOMv9psVsMeOJqpC5giLfwZ0Uic444
关于c# - 当我将 json 字符串反序列化为 C# 对象时,类为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64558973/