添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

Ask Question

I am trying to deserialize just part of my JSON response when I call my function and then return it as a viewmodel but I can't seem to access an inner part of the JSON when I do this. The function in question is this,

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

I am able to setup an HttpClient with a token of an already authenticated user, and now I just need to get information regarding them by making a call to my API. Here is the viewmodel I am trying to fit the JSON into,

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

And the sample response,

"Success":true, "Message":null, "Result":{ "Id":"BDE6C932-AC53-49F3-9821-3B6DAB864931", "UserName":"user.test", "Email":"[email protected]", "Active":true, "Roles":[

As you can see here, I just want to get the Result JSON and deserialize it into the IdentityUserInfoViewModel but I just can't seem to figure out how to go about doing it. It feels like something simple that I'll be kicking myself in the butt about later but can't seem to grasp what it is. Any ideas?

The data to deserialize into IdentityUserInfoViewModel is actually contained in the "Result" property of your posted JSON. Therefore you need to deserialize into some kind of container object like this:

public class Foo
    public bool Success { get; set; }
    public string Message { get; set; }
    public IdentityUserInfoViewModel Result { get; set; }

Then your can deserialize into that and access the resulting object's Result property:

var o = JsonConvert.DeserializeObject<Foo>(formattedResponse);
var result = o.Result;    // This is your IdentityUserInfoViewModel

You can make the response container generic, so it can contain any kind of result:

public class ResultContainer<T>
    public bool Success { get; set; }
    public string Message { get; set; }
    public T Result { get; set; }

And then:

var container = JsonConvert.DeserializeObject<ResultContainer<IdentityUserInfoViewModel>>(formattedResponse);
var result = container.Result;    // This is your IdentityUserInfoViewModel
                Exactly what I needed thank you. Here I am kicking myself in the butt since I had that container on the server side and didn't even think of casting into that first on my application side. >.< Thanks again.
– tokyo0709
                Jul 6, 2016 at 20:44

Maybe I can help you by showing how I use the Deserializer for 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 });
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.