using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
public int id { get; set; }
public string name { get; set; }
public int parent_id { get; set; }
public abstract class BaseClient
protected virtual async Task<Stream> Download(string uri)
uri = uri + (uri.Contains("?") ? "&" : "?") + "api_key=" + "xxxxx";
var response = await new HttpClient() { BaseAddress = new Uri(uri) }.GetAsync(uri);
return await response.Content.ReadAsStreamAsync();
return new FileStream(@"Question66495660.json",
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true);
protected abstract Task<T> Parse<T>(string uri, string root) where T : class, new();
public async Task<Category> GetCategory(string categoryID)
string uri = "https://api.stlouisfed.org/fred/category?category_id=" + categoryID;
return (await Parse<List<Category>>(uri, "categories"))?.FirstOrDefault();
public class JSONClient : BaseClient
protected override async Task<T> Parse<T>(string uri, string root)
uri = uri + (uri.Contains("?") ? "&" : "?") + "file_type=json";
using var stream = await Download(uri);
var options = new JsonSerializerOptions
AllowTrailingCommas = true,
var dictionary = await JsonSerializer.DeserializeAsync<Dictionary<string, T>>(stream, options);
var pair = dictionary?.Single();
if (pair == null || @pair.Value.Key.Equals(root, StringComparison.Ordinal))
throw new JsonException();
public static async Task Test()
var fileName = @"Question66495660.json";
File.WriteAllText(fileName, GetJson());
var client = new JSONClient();
var category = await client.GetCategory("1");
static string GetJson() => @"{
""name"": ""Trade Balance"",
public static async Task Main(string[] args)
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];