'Deserialize json object to array

I have a Json file that is as below and I would like to create an array of name that includes ["h","hg","g","f"].

[
  {
    "name": "h",
    "dir": "h",
    "valid": false
  },
  {
    "name": "hg",
    "dir": "fg",
    "valid": false
  },
  {
    "name": "g",
    "dir": "f",
    "valid": false
  },
  {
    "name": "f",
    "dir": "fgh",
    "valid": false
  }
]

I have accomplished to get the value of a name, but not an array of all names.

    dynamic data = JArray.Parse(Var.txt); //get text in json file
    string name = data[0].name; //get name from first part
    string dir = data[0].dir;
    bool valid = data[0].valid;
    Console.WriteLine("{0}\n{1}\n{2}",name[0], dir[0], valid); //write


Solution 1:[1]

As an alternative, if you have massive amounts of items in your JSON and don't want to deserialize because you are only and only interested in name, you can operate on System.Text.Json.JsonDocument too.

Given you have the JSON, maybe after you do a file read from .txt:

var txtContent = @"[{""name"": ""h"", ""dir"": ""h"", ""valid"": false }, {""name"": ""hg"",""dir"": ""fg"",""valid"": false},{""name"": ""g"",""dir"": ""f"",""valid"": false},{""name"": ""f"",""dir"": ""fgh"",""valid"": false}]"
var data = JsonDocument.Parse(txtContent);

Then you can leverage RootElement.EnumerateArray():

var list = data.RootElement.EnumerateArray().Select(element => element.GetProperty("name").GetString()).ToList();

However, mind that this is a weakly-typed approach and if you are planning to use that JSON data further and can afford deserializing, I'd rather go with that too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mithgroth