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

时间:2016-07-06 19:54:31

标签: c# json asp.net-web-api json.net httpclient

当我调用我的函数然后将其作为viewmodel返回时,我试图反序列化我的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来获取有关它们的信息。这是我试图使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":[  

      ]
   }
}

正如你在这里看到的,我只想获得Result JSON并将其反序列化为IdentityUserInfoViewModel,但我似乎无法弄清楚如何去做。感觉就像是一件简单的事情,我会在以后屁股上踢自己,但似乎无法理解它是什么。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

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