❔ Sorting a JObject by child values
I have JSON being returned by an API that I'm trying to sort to find the most relevant result. Here's an example of the JSON
I need to work out which track is the most relevant which I was going to by comparing/sorting by playCount/rating values (So Wonders of the universe would be the preferred result above) but I'm struggling to find a good way to sort the track array by the child values.
Can someone point me in the right direction?
10 Replies
If you can specify
tracks
is an JArray, maybe linq is smart enough to allow sorting?
Is it not possible to just deserialize this into an actual class rather than a JObject?
Actually, you can also just specify tracks
as an JObject[]
maybe, and arrays implement linqIt probably is possible to deserialize it into a class I'm just not very familiar with C# classes, my background is PHP/JS so I'm a little out of depth 😅
Considering you mention JObject, you use Newtonsoft for the JSON?
Yea Newtonsoft.Json.Linq
JsonConvert.DeserializeObject<x>(json);
will work
x
is your class
However, JArray
implements IEnumerable
, so you can use Linq on it
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JArray.htmLinq works on IEnumerable
Why not just parse to a normal proper object and then sort it as you need with LINQ?
Thats... what I said 🙃
But considering sorting is the biggest issue here, I do feel like I should mention that sorting works perfectly fine on a JArray
But, of course, deserializing into an actual class with syntax is better
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.