0

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);

    }
Qing Guo
  • 6,041
  • 1
  • 2
  • 10
Patola
  • 515
  • 8
  • 30

1 Answers1

-1

The ideal output should be a flat array with all information.

Try:

public static async Task<T> ReadAsync<T>(string fullPath)
    {
        try
        {
            var jsonData = System.IO.File.ReadAllText(fullPath); 
            var parsedJson = JObject.Parse(jsonData); 
            var arrays = parsedJson.Root.Values()
            .Select(x => new NmpLicense
            {
                licenses = (string)x["licenses"],
                repository = (string)x["repository"],
                publisher = (string)x["publisher"],
                email = (string)x["email"],
                path = (string)x["path"],
                licenseFile = (string)x["licenseFile"],
            }).ToArray();
        }
        catch (JsonException ex)
        {

        }

        return default(T);

    }

result: enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10