Click here to Skip to main content
15,887,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to process JSON data that I've retrieved from a Web API.

C#
HttpResponseMessage response = await client.PostAsJsonAsync(
                   "api/my_report", report_request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsByteArrayAsync();
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var result = JsonSerializer.Deserialize<ienumerable>(content, options);



When I inspect the result variable (above) in debug mode, I see that the entries are enumerated and have this general form;

[0] ValueKind = Object : "{"employee_code":"OU812","employee_name":"Alex","work_date":"2024-02-01","manager_name":"Eddie","manager_code":"5150","worked_hours":1,"division":"ROCK"}"

[1] ValueKind = Object : "{"employee_code":"5309","employee_name":"Jenny","work_date":"2024-02-01","manager_name":"Tutone","manager_code":"867","worked_hours":5,"division":"80S ROCK"}"
...etc


I need to now go through the enumerated list and get access to the elemental data - employee_code, employee_name, etc.

But so far all I can do is access each complete "object":
C#
IEnumerator enumerator = result.GetEnumerator();

int n = 0;
while (enumerator.MoveNext() && n < 5)
{
   Console.WriteLine(enumerator.Current);
   n++;
}

Any help'd be appreciated,
Martin

What I have tried:

I've tried defining a class that matches the JSON data but I get an error that it cannot convert the HTTPResponseExample content to that class. (I can't reproduce the exact error now.)
Posted
Updated 11-Mar-24 15:55pm
v3

1 solution

There are tools to help you convert raw JSON into C# classes. One of my go-to tools is JSON Utils: Generate C#, VB.Net, SQL Table and Java from JSON[^]. I list more in my articles: >Working with Newtonsoft.Json in C# & VB[^] & Working with System.Text.Json in C#[^]. I also discuss in detail how to work with deserializing JSON data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900