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

HttpClient GetAsync and ReadAsStringAsync needed to deserialize just part of a complex JSON response

我在调用我的函数时试图反序列化 JSON 响应的一部分,然后 return 它作为一个视图模型,但我似乎无法访问 return 的内部部分=23=] 当我这样做的时候。有问题的功能是这样的,

// 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 来获取有关他们的信息。这是我试图将 JSON 放入的视图模型,

// 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