delphi 使用superobject实现jsonrpc的http远程调用 good

[delphi] view plain copy
 
  1. procedure TForm5.Button4Click(Sender: TObject);  
  2. var  
  3.   O, item: ISuperObject;  
  4.   Strm: TStringStream;  
  5.   result: string;  
  6.   ctx: TSuperRttiContext;  
  7.   student: TStudent;  
  8. begin  
  9.   //可以参考superobject 的readme.html  
  10.   //json demo https://en.bitcoin.it/wiki/API_reference_%28JSON-RPC%29  
  11.   // {"jsonrpc":"2.0","method":"fuck","params":["hehe",32,4],"id":"1433813750019"}  
  12.   // O := SO('{"jsonrpc":"2.0","method":"fuck","params":["hehe",32,4],"id":"1433813750019"}');  
  13.   // O := SO('{"jsonrpc": "2.0", "method": fuck, "params":["hehe",32,4]}');  
  14.   O := SO(  
  15.     '{"jsonrpc": "2.0", "method": "fuck", "params":["hehe",32,4],"id":"12"}');  
  16.   Strm := TStringStream.Create(O.AsString);  
  17.   try  
  18.     IdHTTP1.Request.ContentType := 'application/json';  
  19.     result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);  
  20.     Memo1.Lines.Add(result);  
  21.     O := SO(result);  
  22.     Memo1.Lines.Add(O.AsObject.S['result']);  
  23.   
  24.     O := SO(  
  25.       '{"jsonrpc":"2.0","method":"getstudent","params":[{"id":1,"name":"name","age":123}],"id":"1433813750240"}');  
  26.     Strm := TStringStream.Create(O.AsString);  
  27.     result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);  
  28.     Memo1.Lines.Add(result);  
  29.     O := SO(result);  
  30.     result := O.AsObject.S['result'];  
  31.     Memo1.Lines.Add(result);  
  32.   
  33.     ctx := TSuperRttiContext.Create;  
  34.     try  
  35.       // json转换为对象  
  36.       student := ctx.AsType<TStudent>(SO(result));  
  37.       ShowMessage(student.name);  
  38.       // 对象转换为json  
  39.       O := ctx.AsJson<TStudent>(student);  
  40.       ShowMessage(O.AsString);  
  41.     finally  
  42.       // ctx.Free;  
  43.     end;  
  44.   
  45.     O := SO(  
  46.       '{"jsonrpc":"2.0","method":"getstudents","params":["xxx"],"id":"1433814568751"}');  
  47.     Strm := TStringStream.Create(O.AsString);  
  48.     result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);  
  49.     Memo1.Lines.Add(result);  
  50.     O := SO(result);  
  51.     Memo1.Lines.Add(O.AsObject.S['result']);  
  52.   
  53.     for item in O['result'] do  
  54.     begin  
  55.   
  56.       student := ctx.AsType<TStudent>(item);  
  57.       ShowMessage(student.name);  
  58.       // ShowMessage(item.AsString);  
  59.     end;  
  60.   finally  
  61.     Strm.Free;  
  62.   end;  
  63. end;  

http://blog.csdn.net/earbao/article/details/46423167

posted @ 2016-03-30 20:41  findumars  Views(1049)  Comments(0Edit  收藏  举报