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

[delphi]view plaincopy

  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. O := SO(
  24. '{"jsonrpc":"2.0","method":"getstudent","params":[{"id":1,"name":"name","age":123}],"id":"1433813750240"}');
  25. Strm := TStringStream.Create(O.AsString);
  26. result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);
  27. Memo1.Lines.Add(result);
  28. O := SO(result);
  29. result := O.AsObject.S['result'];
  30. Memo1.Lines.Add(result);
  31. ctx := TSuperRttiContext.Create;
  32. try
  33. // json转换为对象
  34. student := ctx.AsType<TStudent>(SO(result));
  35. ShowMessage(student.name);
  36. // 对象转换为json
  37. O := ctx.AsJson<TStudent>(student);
  38. ShowMessage(O.AsString);
  39. finally
  40. // ctx.Free;
  41. end;
  42. O := SO(
  43. '{"jsonrpc":"2.0","method":"getstudents","params":["xxx"],"id":"1433814568751"}');
  44. Strm := TStringStream.Create(O.AsString);
  45. result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);
  46. Memo1.Lines.Add(result);
  47. O := SO(result);
  48. Memo1.Lines.Add(O.AsObject.S['result']);
  49. for item in O['result'] do
  50. begin
  51. student := ctx.AsType<TStudent>(item);
  52. ShowMessage(student.name);
  53. // ShowMessage(item.AsString);
  54. end;
  55. finally
  56. Strm.Free;
  57. end;
  58. end;

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