Search code examples
c#dotnet-httpclient

How to get Item1 and Item2 from the response


Code:

string responce = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password); 

responce string is

{ "Item1": "aaa", "Item2": "123" }

How to get Item1 and Item2 values?


Solution

  • If you have imported System.Net.Http.Json, you can use the GetFromJsonAsync<TValue>(HttpClient, Uri, CancellationToken) method to get the response body as Response instance.

    using System.Net.Http.Json;
    
    Response responce = await httpClient.GetFromJsonAsync<Response>(Home.BaseAddr + "LastID?pass=" + Password); 
    

    Otherwise, you should deserialize the JSON.

    using Newtonsoft.Json;
    
    string responceString = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password); 
    
    Response responce = JsonConvert.DeserializeObject<Response>(responceString); 
    
    using System.Text.Json;
    
    string responceString = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password); 
    
    Response responce = JsonSerializer.Deserialize<Response>(responceString);
    
    public class Response
    {
        public string Item1 { get; set; }
        public string Item2 { get; set; }
    }