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

xytpbqjk  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(131)

当我调用函数时,我试图反序列化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中,但我似乎不知道如何去做。这感觉就像是一件简单的事情,我会在后面踢自己的屁股,但似乎不能掌握它是什么。有什么想法吗?

7y4bm7vi

7y4bm7vi1#

要反序列化为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
58wvjzkj

58wvjzkj2#

也许我可以通过演示如何使用JSON的反串行化器来帮助您:

public async Task GetJsonAsync()
    {
        HttpClient client = new();

        HttpResponseMessage response = await client.GetAsync("put in your https");

        if (response.IsSuccessStatusCode)
        {
            rootobjects = JsonSerializer
                  .Deserialize<ObservableCollection<Rootobject>>(await response.Content.ReadAsStringAsync(),
                  new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
        }`

相关问题