C# JSON System.Text.Json - How to extract an object from a dictionary or List<Dictionary<string, object>>(json) ?

TeddyTheDev 20 Reputation points
2023-03-18T23:37:08.3+00:00

Hello,

I am trying to populate embeds with data taken from a JSON file, however I am not familiar with that format.

The JSON file follows this format (it's a single array of objects which all contain the same fields):

 [{
  "Id": "id1",
  "Name": "Name A",
  "Rarity": 0, //int
  "Description": "some description",
  "Command": "some command",
  "Url": "a link",
  "ImageUrl": "another link"
},{
  "Id": "id2",
  "Name": "Name B",
  "Rarity": 1,
  "Description": "another description",
  "Command": "another command",
  "Url": "another link",
  "ImageUrl": "another link"
},{
.
.
.
"Id": "id70",
"Name": "another name",
"Rarity": "0",
"Description": "another description",
"Url": "a link",
"ImageUrl": "another link"}]

I'm then reading the file and assigning it to a variable to then deserialize it using System.Text.Json:

        string text = File.ReadAllText(@"./objects.json");

I couldn't initially access the different values so I decided to try to use a list of dictionaries instead:

        var testvalues = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(text);

I'm using Dictionary<string, object> because of the int values in some fields.

I could then read the whole Key/Value pairs this way:

        for (int i = 0; i < testvalues.Count; i++)
        {
            //foreach (var st in testvalues[i])
            //{
            //    Console.WriteLine(st);
            //}
            foreach (KeyValuePair<string, object> kvp in testvalues[i])
            {
                //Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                Console.WriteLine($"{kvp.Key}" + ": " + $"{kvp.Value}");
            }
        }

I would now like to "extract" a single object from this list, depending on a value I would provide, and I was thinking of something similar to:

        //ClassJson filteredObject = testvalues.Find(x => x.Id == "id1");
        //Console.WriteLine($"Test : {filteredObject}");

Which worked fine to access a single value when I initially used when deserializing as a simple list. Now I'm unsure whether there is something similar that could work for a list of dictionaries (key/value pairs) and if it would be possible to extract the whole object instead of just a single value?
I will try to further read https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-6.0 but I can't seem to figure out how to adapt it to my issue, unfortunately.
Thanks for the help!

Developer technologies Visual Studio Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2023-03-19T09:17:33.22+00:00

    This seems to work:

    Dictionary<string, object> found_object = testvalues.FirstOrDefault( d => d["Id"].ToString( ) == "id1" );
    

    It is probably better to use specific objects instead of Dictionary. It is possible to define a helper converter class that interprets strings as numbers or vice versa.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.