How to parse a json string response using Delphi

青春壹個敷衍的年華 提交于 2021-02-07 12:32:29

问题


I have a rest server returning the next json string:

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

I´d like to parse the response to get a list of all email and regid items.

I have tried the next code but I am getting an AV at (TJSONPair(LItem).JsonString.Value='email')

Any help will be appreciated.

Thanks in advance, Luiz

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;

回答1:


Your problems start here:

jv := TJSONArray(LResult.Get(0));

The problem is that LResult.Get(0) does not return an instance of TJSONArray. In fact it returns an instance of TJSONString. That string has value:

'[{"email":"XXX@gmail.com","regid":"12312312312312312313213w"},{"email":"YYYY@gmail.com","regid":"AAAAAAA"}]'

It looks like you are going to need to parse this string as JSON to extract what you need. Here is some gnarly code that does that. Please excuse its quality because I have no experience at all with the Delphi JSON parser.

{$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.

The big lesson here is to stop using unchecked type casts. Using such casts is asking for trouble. When your data does not match your code, you get unhelpful error messages.



来源:https://stackoverflow.com/questions/31390545/how-to-parse-a-json-string-response-using-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!