C# parsing json file with new Newtonsoft.Json to reteive all occorences of name , track ect

mion shion 241 Reputation points
2021-04-22T00:22:08.127+00:00

Good evening i little lost on how to parse json file,

i have created and downloaded the json file i need form the internet and trying to receive multible artist names and track names that are listed in the json file,

also trying to get the value of the large image link to display,

but unsure on how to do this i have created a download and managed to format it to readable json file as it was all one line,

code i have for this is,

        public async void searchtrackAsync(string track)
        {
            string lookup = "http://ws.audioscrobbler.com/2.0/?method=track.search&track="+track+"&api_key=APIKEY&format=json";

            string json = string.Empty; using (var client = new WebClient()) { json = await client.DownloadStringTaskAsync(lookup); }
            File.WriteAllText(Application.StartupPath + "//lookup.json", json, Encoding.UTF8);
            // Json file by default is one line lets get the formatting correct 

            string jsonfix = File.ReadAllText(Application.StartupPath + @"\lookup.json");



            JToken jt = JToken.Parse(jsonfix);
            string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
            File.WriteAllText(Application.StartupPath + @"\lookup.json", formatted);

        }

and the spits out this file here each file is different but the structure is exactly the same.

JsonFile PastBin

i just want to get all track names artist names and the url plus the artwork usally large,

but have no idea how to do this only really ever worked with small files that i created myself i am using newtonsoft but unsure on how to accoumplish this

any help would be greatly appreciated,

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,005 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,436 Reputation points
    2021-04-22T02:44:08.527+00:00

    Hello,

    The best way is to copy the json into a C# class which generated container classes to express the json. Also, for some properties in your case have colons in the property names which need to be aliased as shown belowin MusicResuls.

    Note this is done with Newtonsoft Json.net NuGet package using .NET 5, C#9 so this line needs to change if using conventional .NET Framework

    DownloadedData musicResultsList = new();  
    

    Classes

    public class DownloadedData   
    {  
        public MusicResults results { get; set; }  
    }  
      
    public class MusicResults  
    {  
        [JsonProperty("opensearch:Query")]  
        public OpensearchQuery opensearchQuery { get; set; }  
        [JsonProperty("opensearch:totalResults")]  
        public string opensearchtotalResults { get; set; }  
        [JsonProperty("opensearch:startIndex")]  
        public string opensearchstartIndex { get; set; }  
        [JsonProperty("opensearch:itemsPerPage")]  
        public string opensearchitemsPerPage { get; set; }  
        public Trackmatches trackmatches { get; set; }  
        public Attr attr { get; set; }  
    }  
      
    public class OpensearchQuery  
    {  
        [JsonProperty("#text")]  
        public string text { get; set; }  
        public string role { get; set; }  
        public string startPage { get; set; }  
    }  
      
    public class Trackmatches  
    {  
        public Track[] track { get; set; }  
    }  
      
    public class Track  
    {  
        public string name { get; set; }  
        public string artist { get; set; }  
        public string url { get; set; }  
        public string streamable { get; set; }  
        public string listeners { get; set; }  
        public Image[] image { get; set; }  
        public string mbid { get; set; }  
    }  
      
    public class Image  
    {  
        public string text { get; set; }  
        public string size { get; set; }  
    }  
      
    public class Attr  
    {  
    }  
    

    Then to validate I created a json file, read the information in a class named FileOperations

    public static DownloadedData ReadMusicResults(string fileName = "lookup.json")  
    {  
        DownloadedData musicResultsList = new();  
      
        if (!File.Exists(fileName)) return musicResultsList;  
      
        var json = File.ReadAllText(fileName);  
        musicResultsList = JsonConvert.DeserializeObject<DownloadedData>(json);  
      
        return musicResultsList;  
      
    }  
    

    Used LINQ/Lambda to do a simple query.

    var query = FileOperations  
        .ReadMusicResults()  
        .results.trackmatches.track  
        .Where(track => track.artist == "Post Malone").ToList();  
    

    Results in the IDE Local window
    90136-figure1.png

    ---
    91034-kpmvp.png


1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,591 Reputation points
    2021-04-22T01:49:31.363+00:00

    Visual Studio has a function that can automatically generate classes according to the Json format.

    90059-1.png

    This feature may require certain workloads such as ASP.NET and web development.

    This is the produced class:

    public class Rootobject  
    {  
        public Results results { get; set; }  
    }  
      
    public class Results  
    {  
        public OpensearchQuery opensearchQuery { get; set; }  
        public string opensearchtotalResults { get; set; }  
        public string opensearchstartIndex { get; set; }  
        public string opensearchitemsPerPage { get; set; }  
        public Trackmatches trackmatches { get; set; }  
        public Attr attr { get; set; }  
    }  
      
    public class OpensearchQuery  
    {  
        public string text { get; set; }  
        public string role { get; set; }  
        public string startPage { get; set; }  
    }  
      
    public class Trackmatches  
    {  
        public Track[] track { get; set; }  
    }  
      
    public class Track  
    {  
        public string name { get; set; }  
        public string artist { get; set; }  
        public string url { get; set; }  
        public string streamable { get; set; }  
        public string listeners { get; set; }  
        public Image[] image { get; set; }  
        public string mbid { get; set; }  
    }  
      
    public class Image  
    {  
        public string text { get; set; }  
        public string size { get; set; }  
    }  
      
    public class Attr  
    {  
    }  
    

    Then we can easily read the Json information into the object, and get the required information from the properties:

                string json =  File.ReadAllText(@"D:\test\txt\test.json");  
                 
                Rootobject rootobject = JsonSerializer.Deserialize<Rootobject>(json);  
      
      
                Track[] tracks = rootobject.results.trackmatches.track;  
      
                foreach (var item in tracks)  
                {  
                    Console.WriteLine(item.artist+" "+item.url);  
                }  
    

    I use System.Text.Json instead of Newtonsoft.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.