且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-26 09:42:10

您的问题从这里开始:

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

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

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"}]'

看起来您将需要将此字符串解析为JSON来提取所需的内容.这是一些粗糙的代码.请原谅它的质量,因为我完全没有使用Delphi JSON解析器的经验.

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.