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.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects. It aims to conform to RFC 7159.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With