Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a TJSONArray in delphi

Tags:

json

delphi

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?

like image 716
ewerst Avatar asked May 10 '26 02:05

ewerst


1 Answers

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.

like image 153
Graymatter Avatar answered May 12 '26 18:05

Graymatter