C
C#2y ago
Scythe

❔ 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
{
"data": {
"total": 2,
"tracks": [
{
"id": 170778,
"type": "0",
"title": "Wicked Wonders",
"playCount": 0,
"rating": 0,
"tags": []
},
{
"id": 210755,
"type": "0",
"title": "The Wonders Of The Universe",
"playCount": 1,
"rating": 3,
"tags": []
}
]
}
}
{
"data": {
"total": 2,
"tracks": [
{
"id": 170778,
"type": "0",
"title": "Wicked Wonders",
"playCount": 0,
"rating": 0,
"tags": []
},
{
"id": 210755,
"type": "0",
"title": "The Wonders Of The Universe",
"playCount": 1,
"rating": 3,
"tags": []
}
]
}
}
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
FusedQyou
FusedQyou2y ago
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 linq
Scythe
ScytheOP2y ago
It 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 😅
FusedQyou
FusedQyou2y ago
Considering you mention JObject, you use Newtonsoft for the JSON?
Scythe
ScytheOP2y ago
Yea Newtonsoft.Json.Linq
FusedQyou
FusedQyou2y ago
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.htm
FusedQyou
FusedQyou2y ago
FusedQyou
FusedQyou2y ago
Linq works on IEnumerable
Angius
Angius2y ago
Why not just parse to a normal proper object and then sort it as you need with LINQ?
FusedQyou
FusedQyou2y ago
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
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server