如何在delphi中对TJSONArray进行排序

ewe*_*rst 1 delphi json

我在delphi中有一个充满TJSONObjects的TJSONArray。给定所有json对象共享的密钥,有没有一种方法可以对json数组进行排序?

Gra*_*ter 6

我前一段时间遇到了这个问题。我没有找到任何可以进行排序的方法,所以最终建立了自己的方法:

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;
Run Code Online (Sandbox Code Playgroud)

您需要确保不释放元素列表,因为在传递列表时SetElements会接管列表。