cxflag203 / superobject

Automatically exported from code.google.com/p/superobject
0 stars 0 forks source link

Patch to support /Date(n)/ format #37

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Request a dataset from Azure datamarket

You'll get something like this:
    {
         "SomeField": "Hello",
         "DateStart": "\/Date(939772800000)\/"
    }

2. Use TSuperRTTIContext.AsType<T>() to parse the json into a record.

type TSomeRec=record SomeField:String; DateStart:TDateTime);
var SomeRec:TSomeRec;
begin
  SomeRec := TSuperRTTIContext.AsType<TSomeRec>  ('{SomeField:"xx",DateStart:"\/Date(939772800000)\/"');
end;

What is the expected output? What do you see instead?

The date doesn't get parsed because of the formatting.

Please provide any additional information below.

Related:
http://stackoverflow.com/questions/206384/how-to-format-a-json-date

/Date(n)/ seems to be a pretty common way to format json dates, and the version 
of serialfromdatetime below supports it.

function serialfromdatetime(ctx: TSuperRttiContext; const obj: ISuperObject; 
var Value: TValue): Boolean;
var
  dt: TDateTime;
  i: Int64;
  s:String;
begin
  case ObjectGetType(obj) of
  stInt:
    begin
      TValueData(Value).FAsDouble := JavaToDelphiDateTime(obj.AsInteger);
      Result := True;
    end;
  stString:
    begin
      s := obj.AsString;
      if Length(s)>length('/Date()') then
        if (pos('/Date(',S)=1) and (S[Length(S)]='/') then
        begin
          Delete(S,Length(S)-1,2);
          Delete(S,1,6);
          Result := TryStrToInt64(S,I);
          if Result then
            TValueData(Value).FAsDouble := JavaToDelphiDateTime(I);
          Exit;
        end;

      if ISO8601DateToJavaDateTime(s, i) then
      begin
        TValueData(Value).FAsDouble := JavaToDelphiDateTime(i);
        Result := True;
      end else
      if TryStrToDateTime(s, dt) then
      begin
        TValueData(Value).FAsDouble := dt;
        Result := True;
      end else
        Result := False;
    end;
  else
    Result := False;
  end;
end;

Original issue reported on code.google.com by woutervannifterick on 29 Nov 2012 at 1:22