question

mionshion-3520 avatar image
0 Votes"
mionshion-3520 asked karenpayneoregon edited

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

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,

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon edited

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



figure1.png (25.5 KiB)
kpmvp.png (2.0 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you this has resolved the issue and workes perfectly,

also huge thank you for your continued support on all my comments i post here you are the one that always gives the easy to explain answer and also when i look online for a subject and click on a tread i find most of the time you give the answer that resolves issues so a huge thank you for your continued support on these forms

0 Votes 0 ·

Your welcome :-)

0 Votes 0 ·
TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered karenpayneoregon commented

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.


1.png (20.0 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

i seem to be getting the following error when i try and run this,

 System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'
0 Votes 0 ·

Did you use package manager to install the dll?

Install-Package System.Buffers -Version 4.5.1

And make sure if .NET Core under dependencies you don't get

90203-exclamationtriangle12x12.png


0 Votes 0 ·