I have a TJSONArray filled with TJSONObjects in delphi. Is there a method that will sort the json array given a key that all the json objects share?
I ran into this problem a while back. I didn't find any methods that could do the sorting so ended up building my own:
procedure SortJsonArray(aJsonArray: TJsonArray)
var
cntr: Integer;
elementList: TList<TJSONValue>;
begin
// Sort the elements. We have to sort them because they change constantly
elementList := TList<TJSONValue>.Create;
try
// Get the elements
for cntr := 0 to aJsonArray.Count - 1 do
elementList.Add(aJsonArray.Items[cntr]);
elementList.Sort(TComparer<TJSONValue>.Construct(
function(const Left, Right: TJSONValue): Integer
var
leftObject: TJSONObject;
rightObject: TJSONObject;
begin
// You should do some error checking here and not just cast blindly
leftObject := TJSONObject(Left);
rightObject := TJSONObject(Right);
// Compare here. I am just comparing the ToStrings but you will probably
// want to compare something else.
Result :=
TComparer<string>.Default.Compare(leftObject.ToString, rightObject.ToString);
end));
aJsonArray.SetElements(elementList);
except
on E: Exception do
begin
// We only free the element list when there is an exception because SetElements
// takes ownership of the list.
elementList.Free;
raise;
end;
end;
end;
You need to make sure that you don't free the element list because SetElements takes over the list when you pass in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With