2016-07-06 17 views
1

我想,當我把我的函數,然後返回它作爲一個視圖模型反序列化只是我的JSON響應的一部分,但我似乎無法訪問內我這樣做時JSON的一部分。有問題的功能是這樣的,HttpClient的GetAsync和ReadAsStringAsync需要反序列化只是一個複雜的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":"[email protected]", 
     "Active":true, 
     "Roles":[ 

     ] 
    } 
} 

正如你可以看到這裏,我只想得到結果JSON,並將其反序列化爲在IdentityUserInfoViewModel但我似乎無法弄清楚如何去這樣做。這感覺就像簡單的東西,我會在屁股後話被踢自己,但似乎無法把握它是什麼。有任何想法嗎?

回答

3

反序列化到IdentityUserInfoViewModel的數據實際上是包含在您發佈的JSON的「結果」屬性。因此,你需要反序列化到某種容器對象是這樣的:

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 
+0

正是我需要謝謝。在這裏,我踢我的屁股,因爲我已經在服務器端該容器,甚至沒有想到鑄造成先上我的應用程序的一面。 >。<再次感謝。 – tokyo0709

相關問題