views:

103

answers:

2

Hello, 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.

+2  A: 

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

Daniele Teti
A: 

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;
skamradt