在C#中,我制作了一个GET reqeust来获取一些JSON数据。在这个JSON数据中有一个数组,我想返回这个数据中的元素。我正在使用Json.NET来尝试实现这一点。
以下是我在JSON文件中获取属性的C#代码。
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;
}
上面的代码是我如何在customer下返回客户的名称。但在customer下面有一个数组"active_digital_subscriptions"。在这个数组中,有两个元素我想访问并保存在setting.setting中。"active_digital_subscriptions"只包含字符串。
JSON数据:
{
"response":{
"code":200,
"status":"success",
"data":{
"customer":{
"id":"109701",
"email":"ahjune152@one.com",
"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"
}
]
}
}
}
}
您可以将SelectToken
和SelectTokens
用于此目的。两者都支持JSONPath查询语法:
var userName = (string)Juser.SelectToken("data.customer.name");
var customersItems = Juser.SelectTokens("data.customer.customers_items[*]")
.Select(t => (string)t)
.ToArray();
[*]
是一个通配符,用于选择数组中的所有元素。
更新
考虑到您修改后的JSON,您可以获得活动用户和活动订阅,如下所示:
var userName = (string)Juser.SelectToken("data.customer.name");
var activeSubscriptions = Juser.SelectTokens("data.customer.active_digital_subscriptions[*]")
.Select(t => new { PlanId = (string)t["plan_id"], PlanTitle = (string)t["plan_title"] })
.ToArray();
请注意,活动订阅在一个数组中,因此可能存在多个订阅。如果你知道只有一个,你可以做
var activeSubscription = activeSubscriptions.SingleOrDefault();
在这里,我以匿名类型返回订阅,但如果您愿意,可以定义一个显式类:
public class Subscription
{
public string PlanId { get; set; }
public string PlanTitle { get; set; }
}
然后做:
var activeSubscriptions = Juser.SelectTokens("data.customer.active_digital_subscriptions[*]")
.Select(t => new Subscription { PlanId = (string)t["plan_id"], PlanTitle = (string)t["plan_title"] })
.ToArray();
你可以试试这个-
var subs = (JArray)JObject.Parse(json)["response"]["data"]["customer"]["active_digital_subscriptions"];
for (var i = 0; i < subs.Count; ++i)
{
var id = ((JValue)subs[i]["plan_id"]).Value;
var title = ((JValue)subs[i]["plan_title"]).Value;
}