How to get the Keys values of a Keyvaluepair c#object?

Asked

Viewed 24 times

-1

I have a Json with the following structure:

{
 "Data" {
     "Request": [
      {
        "text": "Minha Pergunta?",
        "response": "Minha resposta"
      }
    ]
  }
}

I do as follows to receive the values in the code:

IConfigurationSection result = _config.GetSection("Data").GetSection("Request");
var itemArray = result.AsEnumerable();
string valor;

Then I make a foreach to go through the whole list:

foreach (var item in itemArray)
   {
      valor = item.Value
   }

However, in this way the variable valor is receiving property value text of my json array. I need to receive the value that is in response

How can I do?

1 answer

1


It is possible to navigate the Keys, and one option is to use a Dictionary. Taking advantage of this, if the structure is always the same in the values (text, Response), you can create a class with this structure and use a typed object, much easier to navigate and iterate, for example:

public class RequestData
{
    public string Text { get; set; }
    public string Response { get; set; }
}

And cast the da Section tipin', like this:

var result = _config
    .GetSection("Data")
    .Get<IDictionary<string, IList<RequestData>>>();

And sail like this:

foreach (var item in result)
{
    Console.WriteLine(item.Key);
    Console.WriteLine("================");
    foreach(var subItem in item.Value)
    {
        Console.WriteLine($"{subItem.Text}: {subItem.Response}");
    }
}

You can see a working example, adapted to a json string here: https://dotnetfiddle.net/HDD1un

  • Good, it worked, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.