gpt4 book ai didi

c# - HttpClient GetAsync 和 ReadAsStringAsync 需要反序列化复杂 JSON 响应的一部分

转载 作者:太空宇宙 更新时间:2023-11-03 23:13:14 25 4
gpt4 key购买 nike

当我调用我的函数时,我试图反序列化我的 JSON 响应的一部分,然后将其作为 View 模型返回,但是当我这样做时,我似乎无法访问 JSON 的内部部分。有问题的功能是这样的,

// GetUserInfoTest method gets the currently authenticated user's information from the Web API
public IdentityUserInfoViewModel GetUserInfo()
{
using (var client = new WebClient().CreateClientWithToken(_token))
{
var response = client.GetAsync("http://localhost:61941/api/Account/User").Result;
var formattedResponse = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<IdentityUserInfoViewModel>(formattedResponse, jsonSettings);
}
}

我可以使用已通过身份验证的用户的 token 设置 HttpClient,现在我只需要通过调用我的 API 来获取有关他们的信息。这是我试图将 JSON 放入的 View 模型,

// Custom view model for an identity user
/// <summary>Custom view model to represent an identity user and employee information</summary>
public class IdentityUserInfoViewModel
{
/// <summary>The Id of the Identity User</summary>
public string Id { get; set; }

/// <summary>The Username of the Identity User</summary>
public string UserName { get; set; }

/// <summary>The Email of the Identity User</summary>
public string Email { get; set; }

/// <summary>Active status of the user</summary>
public bool Active { get; set; }

/// <summary>The Roles associated with the Identity User</summary>
public List<string> Roles { get; set; }
}

以及示例响应,

{  
"Success":true,
"Message":null,
"Result":{
"Id":"BDE6C932-AC53-49F3-9821-3B6DAB864931",
"UserName":"user.test",
"Email":"user.test@testcompany.com",
"Active":true,
"Roles":[

]
}
}

正如您在此处看到的,我只想获取结果 JSON 并将其反序列化为 IdentityUserInfoViewModel,但我似乎无法弄清楚如何去做。感觉就像是一件简单的事情,我稍后会责备自己,但似乎无法理解它是什么。有什么想法吗?

最佳答案

要反序列化为 IdentityUserInfoViewModel 的数据实际上包含在您发布的 JSON 的“Result”属性中。因此,您需要像这样反序列化为某种容器对象:

public class Foo
{
public bool Success { get; set; }
public string Message { get; set; }
public IdentityUserInfoViewModel Result { get; set; }
}

然后您可以对其进行反序列化并访问结果对象的 Result 属性:

var o = JsonConvert.DeserializeObject<Foo>(formattedResponse);
var result = o.Result; // This is your IdentityUserInfoViewModel

您可以使响应容器通用,因此它可以包含任何类型的结果:

public class ResultContainer<T>
{
public bool Success { get; set; }
public string Message { get; set; }
public T Result { get; set; }
}

然后:

var container = JsonConvert.DeserializeObject<ResultContainer<IdentityUserInfoViewModel>>(formattedResponse);
var result = container.Result; // This is your IdentityUserInfoViewModel

关于c# - HttpClient GetAsync 和 ReadAsStringAsync 需要反序列化复杂 JSON 响应的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38232663/

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