Home > front end >  C# Get JSON Keys from Array without Model
C# Get JSON Keys from Array without Model

Time:05-30

I have a JSON file

{
    "RandonName": [
      {
        "RandomKey1": "Data",
        "RandomKey2": "Data",
        "RandomKey3": "Data",
        "RandomKey4": "Data",
        "RandomKey5": "Data"

      },
      {
        "RandomKey1": "Data",
        "RandomKey2": "Data",
        "RandomKey3": "Data",
        "RandomKey4": "Data",
        "RandomKey5": "Data"

      }
    ]
}

My Deserializer

JsonTextReader JTR = new JsonTextReader(stringReader);
JsonSerializer JS = new JsonSerializer();

var dictonary = JS.Deserialize(JTR) as IEnumerable<KeyValuePair<string, JToken>>;

My Print, output is RandonName

foreach(KeyValuePair<string, JToken> pair in sourceRoot)
{
    Console.WriteLine(pair.Key);               
}

Can I get somehow all Key names inside the array?

CodePudding user response:

JsonSerializer.Deserialize() is a static method. You don't need to create instance for JsonSerializer.

Meanwhile JToken is from Newtonsoft.Json. I think would be great not to mix up with System.Text.Json and Newtonsoft.Json.

And deserialize as Dictionary<string, List<Dictionary<string, string>>> type.

Dictionary<string, List<Dictionary<string, string>>> dictonary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(JTR);

// Iterate for first item in RandonName dictionary
foreach (KeyValuePair<string, string> kvp in dictonary["RandonName"][0])
{
    Console.WriteLine(kvp.Key);
    Console.WriteLine(kvp.Value);
}
                
// Iterate for all items in RandonName dictionary
foreach (var items in dictonary["RandonName"])
{
    foreach (KeyValuePair<string, string> kvp in items)
    {
        Console.WriteLine(kvp.Key);
        Console.WriteLine(kvp.Value);
    }       
}

Sample .NET Fiddle

To get all Keys (from the first item):

dictonary["RandonName"][0].Keys

To get all keys from every item in the list:

using System.Linq;

dictonary["RandonName"].SelectMany(x => x.Keys).ToList();

CodePudding user response:

If you need only just the property names from the first object then you can take advantage of Json.NET's Linq

var semiParsedJson = JObject.Parse(json);
var collection = (JArray)semiParsedJson["RandonName"];
var firstObject = (JObject)collection.First();
foreach (var property in firstObject.Properties())
{
    Console.WriteLine(property.Name);
}

CodePudding user response:

    string json = @"{
    'RandonName': [

      {
        'RandomKey1': 'Data',
        'RandomKey2': 'Data',
        'RandomKey3': 'Data',
        'RandomKey4': 'Data',
        'RandomKey5': 'Data'


      },
      {
        'RandomKey1': 'Data',
        'RandomKey2': 'Data',
        'RandomKey3': 'Data',
        'RandomKey4': 'Data',
        'RandomKey5': 'Data'
      }
    ]
}
";
    Console.WriteLine(
      JObject.Parse(json)["RandonName"][0].Children<JProperty>().Select(x => x.Name));

Will print out:

RandomKey1
RandomKey2
RandomKey3
RandomKey4
RandomKey5

The key to the one-liner is to cast the children of the first JObject to JProperty.

  • Related