Home > front end >  C# How to select specific values from a JSON-File using JSON-Text-Reader
C# How to select specific values from a JSON-File using JSON-Text-Reader

Time:06-23

im having the following problem:

I am making a programm, where it loads a JSON-File, but i need only 2 specific values. I already installed the Newtonsoft-Extension for the JSON-File-reading.

This is the JSON-File (i replaced the values with "example"):

 "installed": [
    {
        "name": "example",
        "homepage": null,
        "source": "example",
        "version": "2.0.5",
        "latest": "2.1.5",
        "latest-status": "example",
        "description": "example",
        "abandoned": false
    },
    {
        "name": "example",
        "homepage": "example",
        "source": "example",
        "version": "v2.11.1",
        "latest": "v2.16.0",
        "latest-status": "semver-safe-update",
        "description": "example",
        "abandoned": false
    },
    {
        "name": "examplename",
        "homepage": "https://example.com",
        "source": "example",
        "version": "v9.8.1",
        "latest": "v9.18.0",
        "latest-status": "semver-safe-update",
        "description": "example",
        "abandoned": false

But i only need the "name" the following Name and the "version" the following version.

I already tried filtering after "name", but then i just get "name" as output and not the following name. Is it possible to say somethink like "Return me the "name" name? Here is the code so far:

string fileName = "D:\\Test.json";
        string jsonString = File.ReadAllText(fileName);
        JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));
        while (reader.Read())
        {
            if (reader.Value != null)
            {
                if (reader.Value.ToString() == "name")
                {
                    Console.WriteLine(reader.Value);
                }
            }
            else
            {
                Console.WriteLine("");
            }
        }

Thank you for your help :)

CodePudding user response:

public class Software
{
     public string name {get; set;}
     public string version {get; set;}
     // list all required properties here...
}


public class Installed
{
     public List<Software> installed {get; set;}
}

public class Foo 
{
    public Installed GetInstalledSoftware(string fileName)
    {
        string json;
        using (var reader = File.OpenText(fileName))
        {
            json = reader.ReadToEnd();
        }
        return JsonConvert.DeserializeObject<Installed>(json);
    }
}

If you only want to dump the info to console just call GetInstalledSoftware like this:

public void Dump()
{
    var installedSoftware = GetInstalledSoftware("myPath");
    foreach (var software in installedSoftware.installed)
         Console.WriteLine($"{software.name} - {software.version}");
}
  • Related