How do I read a json file in .net.
The issue is parent element is unique so it is hard to create a class to represent this structure. When I use the code below it returns an empty array. When I try to convert this in an online tool to C# model, it creates a new class for each element.
The ideal output should be a flat array with all information.
{
"@adobe/css-tools@4.2.0": {
"licenses": "MIT",
"repository": "https://github.com/adobe/css-tools",
"publisher": "TJ Holowaychuk",
"email": "tj@vision-media.ca",
"path": "\\node_modules\\@adobe\\css-tools",
"licenseFile": "\\node_modules\\@adobe\\css-tools\\LICENSE"
},
"@ampproject/remapping@2.2.0": {
"licenses": "Apache-2.0",
"repository": "https://github.com/ampproject/remapping",
"publisher": "Justin Ridgewell",
"email": "jridgewell@google.com",
"path": "\\node_modules\\@ampproject\\remapping",
"licenseFile": "\\node_modules\\@ampproject\\remapping\\LICENSE"
},
"@angular-devkit/architect@0.1402.11": {
"licenses": "MIT",
"repository": "https://github.com/angular/angular-cli",
"publisher": "Angular Authors",
"path": "\\node_modules\\@angular-devkit\\architect",
"licenseFile": "\\node_modules\\@angular-devkit\\architect\\LICENSE"
}
}
This is the class I have
public class NmpLicense
{
public string licenses { get; set; }
public string repository { get; set; }
public string publisher { get; set; }
public string email { get; set; }
public string path { get; set; }
public string licenseFile { get; set; }
}
And this is how I read the file
public static async Task<T> ReadAsync<T>(string filePath)
{
try
{
using FileStream stream = File.OpenRead(filePath);
return await JsonSerializer.DeserializeAsync<T>(stream);
}
catch (JsonException ex)
{
}
return default(T);
}