如何从 API 转换一些 RAW 数据并将其保存到变量中,以便我可以在 C# 中使用它们 [英] How to convert some RAW data from an API and save it into variables so i can work with them in C#
问题描述
我正在做一个个人项目.它是一个 C# 应用程序,使用 API 与一些网络服务进行通信.
I'm working on a personal project. Its a C# app that communicates with some web services using an API.
我终于用这几行得到了第一个原始数据:
i finally got the first raw data with this few lines:
var client = new RestClient("https://api.abcd.com/token");
var request = new RestRequest(Method.POST);
request.AddParameter("username", usr);
request.AddParameter("password", pass);
request.AddParameter("grant_type", "password");
在邮递员中,响应(JSON)如下所示:
and in postman the response (JSON) looks like :
{"access_token":"aaaaaaa","token_type":"bearer","expires_in":899,"refresh_token":"bbbbbbb",".issued":"星期五,2020 年 5 月 1 日 16:11:36 GMT",".expires":"2020 年 5 月 1 日星期五 16:26:36GMT",".refreshexpires":"2020 年 5 月 1 日星期五 17:11:36 GMT"}
{"access_token":"aaaaaaa","token_type":"bearer","expires_in":899,"refresh_token":"bbbbbbb",".issued":"Fri, 01 May 2020 16:11:36 GMT",".expires":"Fri, 01 May 2020 16:26:36 GMT",".refreshexpires":"Fri, 01 May 2020 17:11:36 GMT"}
我的下一步是找到在 C# 中将这些键/值对分成不同变量的方法,以便我可以使用它们.
my next step is to find the way to separate those key/value pair into different variables in C# so i can work with them.
非常感谢您的帮助.
推荐答案
但我想为了小目的不需要创建一个类,而是使用像这样的弱类型数据结构:
But I guess for small purpose no need to create a class rather use weakly typed data structure like this:
dynamic responseObject = JsonConvert.DeserializeObject(responseString);
//then use every property like this
responseObject.accessToken ...
responseObject.token_type.....
但是您也需要为此使用 Newtonsoft.Json.
But you need to use Newtonsoft.Json for this too.
这篇关于如何从 API 转换一些 RAW 数据并将其保存到变量中,以便我可以在 C# 中使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!