0

I'm looking for a elaborated answer and/or explanation (with examples).

Q: The goal is to parse a JSON file with the following format (example link provided). Only the url(s) should be outputted to the console (using a array).

The expected output is

001
002
003
004
005

JSON Example on Hastebin

I was told repeatedly the answer is....

using System.Text.Json;

var json = "{ \"entries\": [ { \"value\": \"hello\", \"anotherValue\": 0 } ]"
var thing = JsonSerializer.Deserialize<Thing>(json);
foreach (var entry in thing.Entries) {
  // do thing with entry.Value and entry.AnotherValue
}
record Thing(OtherThing[] Entries);
record OtherThing(string Value, int AnotherValue);

But I'm clueless. Though this is a proven method that work?

My progress:

    internal class Thing
    {

        public class Download
        {
            public string sha1 { get; set; }
            public string url { get; set; }
        }

        public class Root
        {
            public string _id { get; set; }
            public string name { get; set; }
            public string description { get; set; }
            public string image { get; set; }
            public string url { get; set; }
            public List<Download> download { get; set; }
        }
        public void LoadJson()
        {
            using (StreamReader r = new StreamReader("test2json.json"))
            {
                string json = r.ReadToEnd();
                Root file = JsonConvert.DeserializeObject<Root>(json);
                Trace.WriteLine(json);
            }
        }

In a similar method...I was able to parse a JSON url using...

             //Parse JSON Directory. 
var fileName = (@"C:\Users\Icarus\Desktop\test2json.json");
dynamic json = JsonConvert.DeserializeObject(File.ReadAllText(fileName));
string SearchFor = json["Name"]["Url"];

But this is not a desired result.

I'm using C# and the application uses WPF.

dbc
  • 104,963
  • 20
  • 228
  • 340
Cherarium
  • 1
  • 6
  • From your sample json, `Root.url` doesn't exist. In your `LoadJson` method you should be able to `return file.Download.Select(d => d.url).ToArray()` – Jeremy Lakeman Feb 10 '22 at 02:04
  • You need to make your c# classes match your JSON. To do that see [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182). – dbc Feb 10 '22 at 13:07

1 Answers1

0

Firstly, you need to create model class which represents properties of the json object. For example based on your json file, you can create the following class:

public class RootItem // or whatever name of the root object
{
    [JsonPropertyName("_id")]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

    [JsonPropertyName("download")]
    public IEnumerable<Download> Downloads { get; set; }
}

public class Download 
{
    public string Sha1 { get; set; }
    public string Url { get; set; }
}

Secondly, you need to deserialize object (extracting data from a json file). You can use built-in json serializer from System.Text.Json, or you can use Newtonsoft.Json if you are using old frameworks.

In the following example I used default System.Text.Json serializer:

var jsonData = File.ReadAllText("here path of the json file");
var serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var rootObj = JsonSerializer.Deserialize<RootItem>(jsonData, serializerOptions);

Then get whatever data from deserialized object (in our case it's rootObj) If you want to print all urls then you can do something like:

foreach(var download in rootObj.Downloads)
{
    Console.WriteLine(download.Url)
}