delphi 使用superobject实现jsonrpc的http远程调用 good
- procedure TForm5.Button4Click(Sender: TObject);
- var
- O, item: ISuperObject;
- Strm: TStringStream;
- result: string;
- ctx: TSuperRttiContext;
- student: TStudent;
- begin
- //可以参考superobject 的readme.html
- //json demo https://en.bitcoin.it/wiki/API_reference_%28JSON-RPC%29
- // {"jsonrpc":"2.0","method":"fuck","params":["hehe",32,4],"id":"1433813750019"}
- // O := SO('{"jsonrpc":"2.0","method":"fuck","params":["hehe",32,4],"id":"1433813750019"}');
- // O := SO('{"jsonrpc": "2.0", "method": fuck, "params":["hehe",32,4]}');
- O := SO(
- '{"jsonrpc": "2.0", "method": "fuck", "params":["hehe",32,4],"id":"12"}');
- Strm := TStringStream.Create(O.AsString);
- try
- IdHTTP1.Request.ContentType := 'application/json';
- result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);
- Memo1.Lines.Add(result);
- O := SO(result);
- Memo1.Lines.Add(O.AsObject.S['result']);
- O := SO(
- '{"jsonrpc":"2.0","method":"getstudent","params":[{"id":1,"name":"name","age":123}],"id":"1433813750240"}');
- Strm := TStringStream.Create(O.AsString);
- result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);
- Memo1.Lines.Add(result);
- O := SO(result);
- result := O.AsObject.S['result'];
- Memo1.Lines.Add(result);
- ctx := TSuperRttiContext.Create;
- try
- // json转换为对象
- student := ctx.AsType<TStudent>(SO(result));
- ShowMessage(student.name);
- // 对象转换为json
- O := ctx.AsJson<TStudent>(student);
- ShowMessage(O.AsString);
- finally
- // ctx.Free;
- end;
- O := SO(
- '{"jsonrpc":"2.0","method":"getstudents","params":["xxx"],"id":"1433814568751"}');
- Strm := TStringStream.Create(O.AsString);
- result := IdHTTP1.Post('http://10.0.0.107/json_server/server.php', Strm);
- Memo1.Lines.Add(result);
- O := SO(result);
- Memo1.Lines.Add(O.AsObject.S['result']);
- for item in O['result'] do
- begin
- student := ctx.AsType<TStudent>(item);
- ShowMessage(student.name);
- // ShowMessage(item.AsString);
- end;
- finally
- Strm.Free;
- end;
- end;
http://blog.csdn.net/earbao/article/details/46423167