当我调用函数时,我试图反序列化JSON响应的一部分,然后将其作为视图模型返回,但是当我这样做时,我似乎无法访问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);
}
}
我可以使用已经过身份验证的用户的令牌来设置HttpClient,现在我只需要通过调用我的API来获取有关它们的信息。
// 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中,但我似乎不知道如何去做。这感觉就像是一件简单的事情,我会在后面踢自己的屁股,但似乎不能掌握它是什么。有什么想法吗?
2条答案
按热度按时间7y4bm7vi1#
要反序列化为
IdentityUserInfoViewModel
的数据实际上包含在发布的JSON的“Result”属性中,因此需要反序列化为某种容器对象,如下所示:然后,您可以反序列化为该对象,并访问结果对象的
Result
属性:您可以将响应容器设置为泛型,这样它就可以包含任何类型的结果:
然后:
58wvjzkj2#
也许我可以通过演示如何使用JSON的反串行化器来帮助您: