Reputation: 1697
In C# I make a GET reqeust to get som JSON data. In this JSON data there is an array, which I want to return the elements in this data. I'm using Json.NET to try to achieve this.
Here is my C# code to get a property in the JSON file.
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;
}
The code above is how I return the name of a customer under customer. But under customer there is an array, "active_digital_subscriptions". In this array there is 2 elements which I want to access and save in setting.setting. "active_digital_subscriptions" only contains string.
JSON data:
{
"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"
}
]
}
}
}
}
Upvotes: 0
Views: 3582
Reputation: 3726
You could try this -
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;
}
Upvotes: 1
Reputation: 117036
You can use SelectToken
and SelectTokens
for this purpose. Both support JSONPath query syntax:
var userName = (string)Juser.SelectToken("data.customer.name");
var customersItems = Juser.SelectTokens("data.customer.customers_items[*]")
.Select(t => (string)t)
.ToArray();
[*]
is a wildcard that selects all elements in the array.
Update
Given your revised JSON, you can get the active user and active subscriptions like so:
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();
Note that the active subscriptions are in an array, so it would appear possible that there could be more than one. If you know there is only one, you can do
var activeSubscription = activeSubscriptions.SingleOrDefault();
Here I am returning the subscriptions in an anonymous type but you could define an explicit class if you prefer:
public class Subscription
{
public string PlanId { get; set; }
public string PlanTitle { get; set; }
}
And then do:
var activeSubscriptions = Juser.SelectTokens("data.customer.active_digital_subscriptions[*]")
.Select(t => new Subscription { PlanId = (string)t["plan_id"], PlanTitle = (string)t["plan_title"] })
.ToArray();
Upvotes: 3