0

如何获取仅包含名称和标志的 JSON?

  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;

通常用于该类的所有字段:

var
  User: TUser
  sJson: string;

sJson := User.AsJson;

但有时我只需要一个带有名称和标志字段的 JSON。目前,为了获得这样的 JSON,我使用这样的代码:

var
  User: TUser
  usr: ISuperObject;
  sJson: string;

usr := SO(User.AsJson);
usr.Remove('Fields');
usr.Remove('Created');
sJson := usr.AsJSON;

但我认为不是最佳代码(实际上在实际代码中我有 15 个字段,需要删除 12 个)。如何更快地做到这一点?

更新(另一种方法):

可能这对我的目的会更快更有用吗?

usr := SO('');
usr.S['Name']  := User.Name;
usr.I['Flags'] := User.Flags;
sJson := usr.AsJSON;
4

1 回答 1

0

感谢@NasreddineGalfout,我发现 Neon JSON 库可以做到这一点。使用 INeonConfiguration,我可以选择应序列化的公共或已发布或受保护(或任何组合)属性字段。这是我需要的吗?此外,使用 Neon 进行反序列化比使用 XSuperObject 快 2 倍。

type  
  TUser = class
  private
    FName:  string;
    FFlags: UInt32;
    FFields: UInt32;
    FCreated: TDateTime;
  public
    property Name: string read FName write FName;
    property Flags: UInt32 read FFlags write FFlags;
  published
    property Fields: UInt32 read FFields write FFields;
    property Created: TDateTime read FCreated write FCreated;
    constructor Create;
  end;

function MyToJson(User: TUser): string;
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LWriter: TNeonSerializerJSON;
begin
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  LWriter := TNeonSerializerJSON.Create(Config);
  try
    LJSON := LWriter.ObjectToJSON(User);
    try
      Result := TJSONUtils.ToJSON(LJSON);
    finally
      LJSON.Free;
    end;
  finally
    LWriter.Free;
  end;
end;

procedure MyFromJson(var User: TUser; const AJson: string);
var
  Config: INeonConfiguration;
  LJSON: TJSONValue;
  LReader: TNeonDeserializerJSON;
begin
  LJSON := TJSONObject.ParseJSONValue(AJson);
  if not Assigned(LJSON) then
    Exit;
  Config := TNeonConfiguration.Default.SetVisibility([mvPublic{, mvPublished}]);
  try
    LReader := TNeonDeserializerJSON.Create(Config);
    try
      LReader.JSONToObject(User, LJSON);
    finally
      LReader.Free;
    end;
  finally
    LJSON.Free;
  end;
end;
于 2022-02-09T13:44:21.210 回答