在C#中,我做了一個GET請求以獲取som JSON數據。在這個JSON數據中有一個數組,我想要返回這些數據中的元素。我正在使用Json.NET來嘗試實現這一點。如何在JSON中獲取數組並通過循環獲取其元素
這是我的C#代碼來獲取JSON文件中的屬性。
public static string sendRequest(string url, string method)
{
try
{
// Set reqiued information for api
var httpWebRequest = (HttpWebRequest)WebRequest.Create(main_url + url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", "Bearer " + Current_Access_Token);
httpWebRequest.Accept = "application/json;v=1";
httpWebRequest.Method = method;
// Get adn return responses
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string respStr = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
return respStr;
}
catch (Exception e)
{
MessageBox.Show("No response");
}
return "";
}
public static string GetUserName()
{
string resp = sendRequest("api.php/currentCustomer/", "GET");
JObject jObject = JObject.Parse(resp);
JToken Juser = jObject["response"];
string UserName = (string)Juser["data"]["customer"]["name"];
return UserName;
}
上面的代碼是我如何返回客戶名下的客戶。但是在客戶之下有一個數組,「active_digital_subscriptions」。在這個數組中有2個我想訪問的元素並保存在setting.setting中。 「active_digital_subscriptions」只包含字符串。
JSON數據:
{
"response":{
"code":200,
"status":"success",
"data":{
"customer":{
"id":"109701",
"email":"[email protected]",
"name":"ahjune152",
"first_name":"Loc",
"last_name":"Dai Le",
"registration_date":"2015-06-17",
"last_login_date":"2015-11-05",
"is_newsletter_subscriber":"1",
"digital_password":"YOtI1cuzL18dO3i9T9CBVCiX3lQa3iIPhcWDgiwHxxI=",
"language":{
"id":"1",
"name":"American english",
"code":"en"
},
"currency":{
"id":"1",
"name":"Danske kroner",
"sign":"DKK",
"code":"DKK",
"number":"208"
},
"preferred_platforms":[
],
"active_digital_subscriptions":[
{
"plan_id":"246",
"plan_title":"VIP Partner"
}
]
}
}
}
}
你需要創建'JProperty'和'JArray' – MethodMan
這是什麼樣的「異常處理」? –