如何将Delphi XE 10中JSON字符串返回的日期时间解析为TDateTime
我从一个请求中收到以下JSON:如何将Delphi XE 10中JSON字符串返回的日期时间解析为TDateTime,json,rest,delphi,delphi-10-seattle,Json,Rest,Delphi,Delphi 10 Seattle,我从一个请求中收到以下JSON: { "cdPlayer": 3, "nmPlayer": "Player Name", "dtCreate": "2016-08-24T22:53:31.687", "dtChange": null, "idStatus": true } 我想将dtCreate和dtChange加载到TDateTime。如何正确地做到这一点?没有TJSONDateTime来强制转换GetValue。下面是我当前的代码,我将它转换为一个普通字符串 proc
{
"cdPlayer": 3,
"nmPlayer": "Player Name",
"dtCreate": "2016-08-24T22:53:31.687",
"dtChange": null,
"idStatus": true
}
我想将dtCreate和dtChange加载到TDateTime。如何正确地做到这一点?没有TJSONDateTime
来强制转换GetValue
。下面是我当前的代码,我将它转换为一个普通字符串
procedure TfrmPrincipal.btnInfoClick(Sender: TObject);
var
jsonRoot: TJSONObject;
tokenRequest: TRESTRequest;
tokenResponse: TRESTResponse;
tokenClient: TRESTClient;
tokenAutenticacao: TOAuth2Authenticator;
begin
tokenClient := TRESTClient.Create(nil);
tokenRequest := TRESTRequest.Create(nil);
tokenResponse := TRESTResponse.Create(nil);
tokenAutenticacao := TOAuth2Authenticator.Create(nil);
try
tokenRequest.Client := tokenClient;
tokenRequest.Response := tokenResponse;
tokenRequest.Method := TRESTRequestMethod.rmPUT;
tokenClient.Authenticator := tokenAutenticacao;
tokenAutenticacao.TokenType := TOAuth2TokenType.ttBEARER;
tokenAutenticacao.AccessToken := 'token_string';
tokenClient.BaseURL := 'http://host/url/method';
tokenRequest.Execute;
jsonRoot:= TJSONObject.ParseJSONValue(tokenResponse.JSONText) as TJSONObject;
Memo1.Lines.Add('cdPlayer => ' + jsonRoot.GetValue('cdPlayer').Value);
Memo1.Lines.Add('nmPlayer=> ' + jsonRoot.GetValue('nmPlayer').Value);
Memo1.Lines.Add('dtCreate=> ' + jsonRoot.GetValue('dtCreate').Value);
Memo1.Lines.Add('dtChange=> ' + jsonRoot.GetValue('dtChange').Value);
Memo1.Lines.Add('idStatus=> ' + (jsonRoot.GetValue('idStatus') as TJSONBool).ToString);
finally
tokenAutenticacao.Free;
tokenResponse.Free;
tokenRequest.Free;
tokenClient.Free;
end;
end;
我用的是Delphi XE 10 Seatle。谢谢
编辑
就副本而言,我不知道这个数据格式是ISO8601。这就是为什么我无法通过谷歌找到答案。也许我的问题会帮助像我这样不知道的其他人。我会从该字符串中提取日期的每一部分(年、月、日、小时、分钟、毫秒),并对日期时间值进行编码。这很容易,因为每个部分始终处于相同的位置
function JSONDate_To_Datetime(JSONDate: string): TDatetime;
var Year, Month, Day, Hour, Minute, Second, Millisecond: Word;
begin
Year := StrToInt(Copy(JSONDate, 1, 4));
Month := StrToInt(Copy(JSONDate, 6, 2));
Day := StrToInt(Copy(JSONDate, 9, 2));
Hour := StrToInt(Copy(JSONDate, 12, 2));
Minute := StrToInt(Copy(JSONDate, 15, 2));
Second := StrToInt(Copy(JSONDate, 18, 2));
Millisecond := Round(StrToFloat(Copy(JSONDate, 19, 4)));
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
end;
是 啊我想过要这么做。我只是认为这将是一个内置函数,并处理时区。据我所知,没有标准的JSON日期格式,所以Delphi没有TJSONDateTime类也就不足为奇了。我明白了。它是从.NETWebAPI生成的。我会给它一些时间,看看是否还有其他答案。非常感谢您抽出时间。马克,对您的代码稍加修改,看在posperity的份上,这是StrToFloat.:)不要重新发明轮子我不知道这个格式是ISO 8601。这就是为什么我能找到答案。但确实如此。完全理解。日期转换的底线是,几乎可以肯定的是,所有关于日期的问题都已经被问过了。无论如何,我需要找到他们!