【发布时间】:2018-12-14 20:36:03
【问题描述】:
学习 C#。我正在使用 JSON.net 序列化和反序列化服务器的响应。
我确实有一小部分在工作。例如,对于 OAuth2,我需要发送凭据以获取 access_token。我必须通过以下方式进行:
// Serialize the JSON response for the access_token
public class AccessToken
{
public string access_token { get; set; }
}
static async void GetCrmAccessToken(FormUrlEncodedContent content)
{
try
{
// Send the x-www-form-urlencoded info to the OAuth2 end point
HttpResponseMessage response = await Client.PostAsync("https://login.windows.net/42daf6bc-f7add741ac61/oauth2/token", content);
// Get the body from the response
var responseContent = await response.Content.ReadAsStringAsync();
// Extract out the access token from the repsonse
AccessToken responseBody = JsonConvert.DeserializeObject<AccessToken>(responseContent);
if (responseBody.access_token != "")
{
// If there is an access token, take it and use it in
// generating the query
RequestCrmQuery(responseBody.access_token);
}
else
{
Console.WriteLine("Could not get the access token.");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
基本上必须为我想从 JSON 中取出的键创建一个带有公共变量的类。
现在我有了访问令牌,查询的响应明显更大。
- 是否必须为要使用 JSON 响应的每个键创建一个公共变量? (有几十个)。
- 可以自动序列化吗?如果有,怎么做?
- 服务器响应中的某些键具有疯狂的名称,例如
biz_status@OData.Community.Display.V1.FormattedValue。无法在 C# 中创建具有该名称的变量。这项工作将如何赋予我需要使用的重要关键之一? - 我可以将变量称为其他名称,但在 JSON 中明确说明它对应的键吗?
【问题讨论】:
-
"为每个键创建一个方法"???检查您的主帐户是否搜索过有关从 JSON 自动创建类的信息。
-
是的,不听你说的。
-
请保留每个问题 1 且只有 1 个问题。否则答案将是:是的,是的,this 是的。