如何使用Delphi解析json字符串响应

Lui*_*ves 8 delphi parsing json delphi-xe

我有一个休息服务器返回下一个json字符串:

response:='{"result":["[{\"email\":\"XXX@gmail.com\",\"regid\":\"12312312312312312313213w\"},{\"email\":\"YYYY@gmail.com\",\"regid\":\"AAAAAAA\"}]"]}';
Run Code Online (Sandbox Code Playgroud)

我想解析响应以获取所有emailregid项目的列表.

我已经尝试了下一个代码,但我正在获得AV (TJSONPair(LItem).JsonString.Value='email')

任何帮助将不胜感激.

谢谢,路易斯

var
  LResult:TJSONArray;
  LJsonresponse:TJSONObject;
  i:integer;
  LItem,jv:TJsonValue;
  email,regid:string;

      LJsonresponse:=TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(response),0) as TJSONObject;
      LResult:=(LJsonresponse.GetValue('result') as TJSONArray);
      jv:=TJSONArray(LResult.Get(0));
      for LItem in TJSONArray(jv) do begin
         if (TJSONPair(LItem).JsonString.Value='email') then begin
           email:=TJSONPair(LItem).JsonValue.Value;
         end;
         if (TJSONPair(LItem).JsonString.Value='regid') then begin
           regid:=TJSONPair(LItem).JsonValue.Value;
         end;
      end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 13

你的问题从这里开始:

jv := TJSONArray(LResult.Get(0));
Run Code Online (Sandbox Code Playgroud)

问题是LResult.Get(0)不返回实例TJSONArray.实际上它返回的是一个实例TJSONString.该字符串有价值:

'[{"email":"XXX@gmail.com","regid":"12312312312312312313213w"},{"email":"YYYY@gmail.com","regid":"AAAAAAA"}]'
Run Code Online (Sandbox Code Playgroud)

看起来您需要将此字符串解析为JSON以提取您需要的内容.这是一些粗糙的代码.请原谅其质量,因为我对Delphi JSON解析器没有任何经验.

{$APPTYPE CONSOLE}

uses
  SysUtils, JSON;

const
  response =
    '{"result":["[{\"email\":\"XXX@gmail.com\",\"regid\":\"12312312312312312313213w\"},'+
    '{\"email\":\"YYYY@gmail.com\",\"regid\":\"AAAAAAA\"}]"]}';

procedure Main;
var
  LResult: TJSONArray;
  LJsonResponse: TJSONObject;
  ja: TJSONArray;
  jv: TJSONValue;
begin
  LJsonResponse := TJSONObject.ParseJSONValue(response) as TJSONObject;
  LResult := LJsonResponse.GetValue('result') as TJSONArray;
  ja := TJSONObject.ParseJSONValue(LResult.Items[0].Value) as TJSONArray;
  for jv in ja do begin
    Writeln(jv.GetValue<string>('email'));
    Writeln(jv.GetValue<string>('regid'));
  end;
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)

这里的重要教训是停止使用未经检查的类型转换.使用这样的演员阵容会遇到麻烦.当您的数据与您的代码不匹配时,您将收到无用的错误消息.