gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:46:24 29 4
gpt4 key购买 nike

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

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

我想解析响应以获取所有电子邮件regid项目的列表。

我已尝试下一个代码,但我在 (TJSONPair(LItem).JsonString.Value='email') 处收到 AV

任何帮助将不胜感激。

提前致谢,路易斯

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;

最佳答案

您的问题从这里开始:

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

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

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

看起来您需要将此字符串解析为 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.

这里的重要教训是停止使用未经检查的类型转换。使用这样的强制类型转换是自找麻烦。当您的数据与代码不匹配时,您会收到无用的错误消息。

关于json - 如何使用 Delphi 解析 json 字符串响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31390545/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com