我有一个休息服务器返回下一个json字符串:
response:='{"result":["[{\"email\":\"[email protected]\",\"regid\":\"12312312312312312313213w\"},{\"email\":\"[email protected]\",\"regid\":\"AAAAAAA\"}]"]}';
我倒是喜欢解析响应以获取所有的清单email
和regid
项目。
我已经尝试了下一个代码,但是正在获取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;
您的问题从这里开始:
jv := TJSONArray(LResult.Get(0));
问题是LResult.Get(0)
不返回的实例TJSONArray
。实际上,它返回的实例TJSONString
。该字符串具有值:
'[{"email":"[email protected]","regid":"12312312312312312313213w"},{"email":"[email protected]","regid":"AAAAAAA"}]'
看来您将需要将此字符串解析为JSON来提取所需的内容。这是一些粗糙的代码。请原谅它的质量,因为我完全没有使用Delphi JSON解析器的经验。
{$APPTYPE CONSOLE}
uses
SysUtils, JSON;
const
response =
'{"result":["[{\"email\":\"[email protected]\",\"regid\":\"12312312312312312313213w\"},'+
'{\"email\":\"[email protected]\",\"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.
这里的主要教训是停止使用未经检查的类型强制转换。使用这样的强制转换会带来麻烦。如果您的数据与代码不匹配,则会收到无用的错误消息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句