gpt4 book ai didi

c# - 当我将 json 字符串反序列化为 C# 对象时,类为空

转载 作者:行者123 更新时间:2023-12-02 19:09:20 28 4
gpt4 key购买 nike

这是使用 Console.Writeline 打印的 Json 字符串:

{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLmRydW1zdGlrLmFwcFwvYXBpXC9sb2dpbiIsImlhdCI6MTYwMzgxNTcxMywiZXhwIjoxNjAzODE5MzEzLCJuYmYiOjE2MDM4MTU3MTMsImp0aSI6InJhU1dJSHBJaWR0YnhjTUUiLCJzdWIiOjQ1LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.aaQoQVKTSMFWCEOMv9psVsMeOJqpC5giLfwZ0Uic444","token_type":"bearer","expires_in":3600}

enter image description here

我想构建一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com