我在寫一個c#控制臺應用程式,我需要從一個webapi獲取某個JSON日期。 在大多數情況下,這一切都很正常,但是在我的一個JSON回應中,我得到了一個用@盯著的屬性名稱。我似乎不知道如何將該JSON屬性放入C#物件中。
我的代碼如下:
public class AlertResponse
{
public string @class { get; set; }
public string result { get; set; }
public string info { get; set; }
}
public class AuthenticationResponse
{
public string Access_token { get; set; }
}
class Test; }
{
private static HttpClient client = new HttpClient()。
private static string BaseURL = "https://xxxxx.xxxx"/span>;
public void Run()
{
client.BaseAddress = new Uri(BaseURL)。
client.DefaultRequestHeaders.Accept.Clear()。
客戶端.DefaultRequestHeaders.Accept.Add()
new MediaTypeWithQualityHeaderValue("application/json") )。
AuthenticationResponse authenticationResponse = Login();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResponse.Access_token) 。
AlertResponse OpenAlerts = GetOpenAlerts()。
}
internal AlertResponse GetOpenAlerts() 。
{
var response = client.GetAsync("/api/v2/xxxxxxxxxxxxxx/alerts/open").Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsync<AlertResponse>().Result。
}
else[/span
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase) 。
}
return null。
}
private AuthenticationResponse Login()
{
string apiKey = "gdfashsfgjhsgfj"/span>;
string apiSecretKey = "sfhsfdjhssdjhsfh";
var byteArray = new UTF8Encoding().GetBytes("public-client:public") 。
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray))。
var form = new FormUrlEncodedContent(new Dictionary<string, string>。{ "username", apiKey }, { "password", apiSecretKey }, { "grant_type", "password" }。});
HttpResponseMessage tokenMessage = client.PostAsync("/auth/oauth/token"/span>, form).Result;
if (tokenMessage.IsSuccessStatusCode)
{
return tokenMessage.Content.ReadAsync<AuthenticationResponse>().Result;
}
else[/span
{
Console.WriteLine("{0} ({1})", (int)tokenMessage.StatusCode, tokenMessage.ReasonPhrase) 。
}
return null。
}
而我得到的JSON看起來是這樣的:
"AlertResponse"/span>: {
"@class"/span>: "patch_ctx",
"patchUid": "afdhgfhjdajafjadfjadfjdj",
"policyUid": "dsgafdhasfjafhdafhadfh",
"result": "0x80240022",
"info": "fdgdfhsfgjh".
}
我怎樣才能解決這個問題?
最好的問候 Glacier
uj5u.com熱心網友回復:
你是使用Newtonsoft.Json還是System.Text.Json?
在這兩種情況下,你都應該用
來裝飾@class屬性。//System.Text.Json。
[JsonPropertyName("@class")/span>]
public string class { get; set; }
或者
//Newtonsoft.Json。
[JsonProperty("@class"/span>)]
public string class { get; set; }
uj5u.com熱心網友回復:
我猜你正在尋找DataMemberAttribute和DataContract
using System.Runtime.Serialization。
[] 。
public class AlertResponse
{
[]
public string Class { get; set; }
[]
public string Result { get; set; }
[]
public string Info { get; set; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332311.html
標籤:
上一篇:如何在獲取資料后設定初始狀態值以更新react中的表單
下一篇:PWAIT_ALL_COMPONENTS_INITIALIZED和WAIT_XTP_HOST_WAIT每次等待的平均毫秒數高。
