Reputation: 103
I have a json file which has random names in roots but same structure in child elements. I would like to get all the child elements in an array or a list.
Sample json file :
{
"-LeHl495vL6vh-8CaLbD":{
"apiKey":"sr-tr-137-beea04e44cb452ba0da0ca090b7e61b4ec6ffc69"
},
"-LeHl6jrhUEMb7slZcpB":{
"apiKey":"sr-tr-137-aef7a23095c0c7baef1ef681bdd8bf9756ac2a17"
}
}
I have tried these classes but could not do it.
public class RequestedReport
{
public Dictionary<string, List<ReportData>> ReportDatas { get; set; }
}
public class ReportData
{
public string apiKey { get; set; }
}
So my expected output from deserialization is like List which contains all the apiKeys in json file.
Thanks in advance.
Upvotes: 8
Views: 2082
Reputation: 1502206
It looks to me like your JSON represents a Dictionary<string, ReportData>
directly. There's no wrapper object, and no lists involved. If you deserialize your JSON to that type, it should be fine. Here's a complete example:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main()
{
var json = File.ReadAllText("test.json");
var reports = JsonConvert.DeserializeObject<Dictionary<string, ReportData>>(json);
foreach (var pair in reports)
{
Console.WriteLine($"{pair.Key}: {pair.Value.ApiKey}");
}
}
}
public class ReportData
{
[JsonProperty("apiKey")]
public string ApiKey { get; set; }
}
If you just want the list of API keys, and you don't care about the field names associated with them, you can use:
var apiKeys = reports.Values.Select(x => x.ApiKey).ToList();
Upvotes: 11