如何使用Delphi解析JSON字符串响应 [英] How to parse a json string response using Delphi
问题描述
我有一个休息服务器返回下一个json字符串:
I have a rest server returning the next json string:
response:='{"result":["[{\"email\":\"XXX@gmail.com\",\"regid\":\"12312312312312312313213w\"},{\"email\":\"YYYY@gmail.com\",\"regid\":\"AAAAAAA\"}]"]}';
我想解析响应以获取所有email
和regid
项目的列表.
I´d like to parse the response to get a list of all email
and regid
items.
我尝试了下一个代码,但是在(TJSONPair(LItem).JsonString.Value='email')
I have tried the next code but I am getting an AV at (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;
推荐答案
您的问题从这里开始:
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.
这篇关于如何使用Delphi解析JSON字符串响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!