【问题标题】:How to parse a json string response using Delphi如何使用 Delphi 解析 json 字符串响应
【发布时间】:2015-10-02 03:23:07
【问题描述】:

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

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

我想解析响应以获取所有 emailregid 项目的列表。

我已经尝试了下一个代码,但我在 (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;

【问题讨论】:

    标签: json delphi parsing delphi-xe


    【解决方案1】:

    你的问题从这里开始:

    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.
    

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

    【讨论】:

    • 太棒了,大卫先生。它工作得很好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多