Delphi 中的自定义编组 TDictionary

发布于 2024-09-29 12:19:33 字数 556 浏览 0 评论 0原文

我需要在 Delphi (XE) 中自定义编组/取消编组 TDictionary。字典声明为:

TMyRecord = record
  key11: integer;
  key12: string;
  ...
end;

TMyDict: TDictionary<string, TMyRecord>;

现在,如果我在不注册自定义转换器的情况下编组字典,则编组器会将所有类型的字段放入 JSON 字符串中 - FOnValueNotify、FKeyCollection、FItems 等。

我需要的是某种关联数组关联数组,即

{"key1":{"key11":"val1","key12":"val2"},"key2":{"key11":"val3","key12":"val4"}}

不幸的是,我不知道如何编写自定义转换器和恢复器。我正在使用 Delphi XE 和内置的 TJSONMarshal 和 TJSONUnMarshal。

注意:此任务不需要使用 TDictionary。我只是不能带来更好的东西。

I need to custom marshal/unmarchal a TDictionary in Delphi (XE). The dictionary is declared as:

TMyRecord = record
  key11: integer;
  key12: string;
  ...
end;

TMyDict: TDictionary<string, TMyRecord>;

Now, if i marshal the dictionary without registering a custom converter, the marshaller will put all kind of fields in the JSON string - FOnValueNotify, FKeyCollection, FItems, etc.

What i need is some sort of associative array of associative arrays, i.e.

{"key1":{"key11":"val1","key12":"val2"},"key2":{"key11":"val3","key12":"val4"}}

Unfortunately, i don't know how to write the custom converter and reverter. I'm using Delphi XE and the built in TJSONMarshal and TJSONUnMarshal.

Note: The use of TDictionary for this task is not required. I just cant come with something better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能否归途做我良人 2024-10-06 12:19:33

对于像您这样的简单情况,我倾向于使用自定义方法来表示 JSON 中的对象。但是,如果您想创建恢复器和转换器,您应该阅读这篇文章:
http://www.danieleteti.it/?p=146

For a simple case like yours, I tend to use a custom method to represent my object in JSON. But, if you want to create reverter and converter, you should read this article:
http://www.danieleteti.it/?p=146

静若繁花 2024-10-06 12:19:33

另一个选项是 TSuperObject,它能够使用 RTTI 与 JSON 进行编组:

type
  TData = record
    str: string;
    int: Integer;
    bool: Boolean;
    flt: Double;
  end;
var
  ctx: TSuperRttiContext;
  data: TData;
  obj: ISuperObject;
begin
  ctx := TSuperRttiContext.Create;
  try
    data := ctx.AsType<TData>(SO('{str: "foo", int: 123, bool: true, flt: 1.23}'));
    obj := ctx.AsJson<TData>(data);
  finally
    ctx.Free;
  end;
end;

Another option is TSuperObject which has the ability to marshal to/from JSON using RTTI:

type
  TData = record
    str: string;
    int: Integer;
    bool: Boolean;
    flt: Double;
  end;
var
  ctx: TSuperRttiContext;
  data: TData;
  obj: ISuperObject;
begin
  ctx := TSuperRttiContext.Create;
  try
    data := ctx.AsType<TData>(SO('{str: "foo", int: 123, bool: true, flt: 1.23}'));
    obj := ctx.AsJson<TData>(data);
  finally
    ctx.Free;
  end;
end;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文