Home > Net >  How to parse/map a JSON in C# and locate specific classes to output
How to parse/map a JSON in C# and locate specific classes to output

Time:02-10

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

I haven't been receiving adequate help from those around me and I feel like nobody explaining what I need in a way I can understand. I almost feel stupid for not getting a solution where everyone else say "that makes sense".

I have been looking at examples...but I just don't get it. I've been applying the code examples and they produce negative results.

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.

Please help me.

I'm using C# and the application is a WPF

CodePudding user response:

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)
}
  •  Tags:  
  • Related