接口数据有如下规范{"error": 0, "msg": "", "data": ...}
其中数据data类型不确定。发生错误时,返回错误代码error与提示msg,反之error为0,msg为""。
function GetResultData(const AStr: string; var AData: string): Boolean; var vJ: ISuperObject; begin vJ := SO(AStr); Result := vJ.I['error'] = 0; if Result then AData := vJ['data'].AsString else AData := Format('错误代码[%d]: %s', [vJ.I['error'], vJ.S['msg']]); end;
1. 解析Json数据为{"error": 0, "msg": "", "data": {"name":"张三","age": 17}}
procedure GetPersonInfo(const AStr: string); var sInfo: string; vPerson: ISuperObject; begin if GetResultData(AStr, sInfo) then begin vPerson := SO(sInfo); ShowMessage(Format('姓名:%s,年龄:%d', [vPerson.S['name'], vPerson.I['age']])); end else MessageBox(0, PChar(sInfo), PChar('警告'), MB_OK or MB_ICONWARNING); end;
2. 解析Json数据为{"error": 0, "msg": "", "data": [{"name":"张三","age": 17},{"name":"李四","age":20}]}
procedure GetPersonsInfo(const AStr: string); var sInfo: string; vPersons, vPerson: ISuperObject; i: Integer; sgs: TStrings; begin if GetResultData(AStr, sInfo) then begin vPersons := SO(sInfo); sgs := TStringList.Create; for i := 0 to vPerson.AsArray.length - 1 do begin vPerson := vPerson.AsArray.O[i]; sgs.Add(Format('姓名:%s,年龄:%d', [vPerson.S['name'], vPerson.I['age']])); end; ShowMessage(sgs.Text); sgs.Free; end else MessageBox(0, PChar(sInfo), PChar('警告'), MB_OK or MB_ICONWARING); end;