-1

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?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
jjctw1969
  • 57
  • 7
  • Maybe it can help https://stackoverflow.com/questions/7332611/how-do-i-extract-value-from-json – DonMiguelSanchez Jul 09 '23 at 06:33
  • 1
    In the [documentaton](https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient) there is an example how to use [GetJsonFormAsync](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.getfromjsonasync) to parse the result into a record class. – Klaus Gütter Jul 09 '23 at 06:37
  • Does this answer your question? [How can I deserialize JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-deserialize-json-with-c) – Charlieface Jul 09 '23 at 12:13

2 Answers2

2

I like the previous solutions, but a straight forward answer would be:

 using System.Text.Json;

 ...

 string s = await httpClient.GetStringAsync(Home.BaseAddr + "LastID?pass=" + Password); 
 var obj = JsonSerializer.Deserialize<Tuple<string,string>>(s);

It is simple as that. Because the Tuple construct is defined with Item1, Item2 as properties and the deserialializer would map it on these.

To get the values:

string item1 = obj.Item1;
string item2 = obj.Item2;
Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
D A
  • 1,724
  • 1
  • 8
  • 19
1

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; }
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46