I get a json string from an external web service. I would like to save the events from the events array in my database. How can I get List<FacebookEvents>?
My current attempt doesn't work:
List< FacebookEvents > my_obj = JsonConvert.DeserializeObject < FacebookEvents > (jsonString);
Source json:
{
"events": [{
"id": "163958810691757",
"name": "3Bridge Records presents inTRANSIT w/ David Kiss, Deep Woods, Eric Shans",
"coverPicture": "https://scontent.xx.fbcdn.net/t31.0-8/s720x720/13679859_10153862492796325_8533542782240254857_o.jpg",
"profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-0/c133.0.200.200/p200x200/13872980_10153862492796325_8533542782240254857_n.jpg?oh=a46813bbf28ad7b8bffb88acd82c7c71&oe=581EF037",
"description": "Saturday, August 20th.\n\nJoin the 3Bridge Records team for another night of sound and shenanigans - as we send Deep Woods & David Kiss out to Burning Man & belatedly celebrate Slav Ka's debut release on the label - \"Endless\" - out May 14th, featuring a remix by Mr. Shans.\n\nDavid Kiss (House of Yes)\nhttps://soundcloud.com/davidkiss\n\nDeep Woods (3Bridge Records)\nhttps://soundcloud.com/deep-woods\n\nEric Shans (3Bridge Records)\nhttps://soundcloud.com/eric-shans\n\nSlav Ka (3Bridge Records)\nhttps://soundcloud.com/slinkyslava\n\nFree before 12, $10 after (+ 1 comp well drink). $5 presale available on RA.\n\nhttps://www.residentadvisor.net/event.aspx?863815\n\nStay dope, Brooklyn.",
"distance": "203",
"startTime": "2016-08-20T22:00:00-0400",
"timeFromNow": 481946,
"stats": {
"attending": 44,
"declined": 3,
"maybe": 88,
"noreply": 1250
},
"venue": {
"id": "585713341444399",
"name": "TBA Brooklyn",
"coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/13932666_1397749103574148_4391608711361541993_n.png?oh=2d82be3a458d1ce9ac8fab47cdbc6e26&oe=585E6545",
"profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/12049351_1300865083262551_8221231831784471629_n.jpg?oh=a30798841ad60dfe5cfabaa4e803c3ad&oe=5854DFB9",
"location": {
"city": "Brooklyn",
"country": "United States",
"latitude": 40.711217064583,
"longitude": -73.966384349735,
"state": "NY",
"street": "395 Wythe Ave",
"zip": "11249"
}
}
},
...
],
"metadata": {
"venues": 1,
"venuesWithEvents": 1,
"events": 4
}}
class FacebookEvents
{
//[JsonProperty(PropertyName = "id")]
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public string description { get; set; }
public string distance { get; set; }
public string startTime { get; set; }
public string timeFromNow { get; set; }
public Stats stats { get; set; }
}
class Stats {
public string attending { get; set; }
public string declined { get; set; }
public string maybe { get; set; }
public string noreply { get; set; }
}
class Venue
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public Location location { get; set; }
}
class Location
{
public string city { get; set; }
public string country { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
You are missing to define your RootObject which Contains List<Event> and Metadata. Full Example
public class RootObject
{
public List<Event> events { get; set; }
public Metadata metadata { get; set; }
}
public class Stats
{
public int attending { get; set; }
public int declined { get; set; }
public int maybe { get; set; }
public int noreply { get; set; }
}
public class Location
{
public string city { get; set; }
public string country { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
public class Venue
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public Location location { get; set; }
}
public class Event
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public string description { get; set; }
public string distance { get; set; }
public string startTime { get; set; }
public int timeFromNow { get; set; }
public Stats stats { get; set; }
public Venue venue { get; set; }
}
public class Metadata
{
public int venues { get; set; }
public int venuesWithEvents { get; set; }
public int events { get; set; }
}
This will work:
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
EDIT:
First this is JSON, here how you can take Venue information.
foreach(var item in result.events)
{
Console.WriteLine(item.venue.name);
}
you need a root object that has an events property to store the collection
public class RootObject {
public IList<FacebookEvents> events {get;set;}
}
and then you will be able to access events
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
var events = root.events;
Related
I'm trying to get the amount of pieces belonging to a certain Lego set using the Brickset API (https://brickset.com/article/52664/api-version-3-documentation)
When writing the Json string to the console it displays the amount of pieces correct. Howeever after deserializing and then writing only the value of pieces to the console it displays 0. All other properties are also not displayed when written to the console.
Result after writing the Json string to the console
{"status":"success","matches":1,"sets":\[
{
"setID": 31844,
"number": "10293",
"numberVariant": 1,
"name": "Santa's Visit",
"year": 2021,
"theme": "Icons",
"themeGroup": "Model making",
"subtheme": "Winter Village Collection",
"category": "Normal",
"released": true,
"pieces": 1445,
"minifigs": 4,
"image": {
"thumbnailURL": "https://images.brickset.com/sets/small/10293-1.jpg",
"imageURL": "https://images.brickset.com/sets/images/10293-1.jpg"
},
"bricksetURL": "https://brickset.com/sets/10293-1",
"collection": {},
"collections": {
"ownedBy": 9350,
"wantedBy": 2307
},
"LEGOCom": {
"US": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"UK": {
"retailPrice": 89.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"CA": {
"retailPrice": 139.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"DE": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
}
},
"rating": 4.3,
"reviewCount": 0,
"packagingType": "Box",
"availability": "LEGO exclusive",
"instructionsCount": 15,
"additionalImageCount": 13,
"ageRange": {
"min": 18
},
"dimensions": {
"height": 28.0,
"width": 47.9,
"depth": 8.7,
"weight": 1.656
},
"barcode": {
"EAN": "5702016914313"
},
"extendedData": {
"tags": \[
"Santa Claus|n",
"18 Plus",
"Baked Goods",
"Bedroom",
"Bird",
"Brick Built Tree",
"Brick Separator",
"Christmas",
"Christmas Tree",
"D2c",
"Fireplace",
"Furniture",
"House",
"Kitchen",
"Light Brick",
"Mail",
"Microscale",
"Musical",
"Rocket",
"Seasonal",
"Winter Village"
\]
},
"lastUpdated": "2022-10-03T08:24:39.49Z"
}
\]}
Main Code
class Program
{
static async Task Main(string[] args)
{
await askSetNumber();
}
private async Task GetPosts(string url)
{
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
Console.WriteLine(response);
var set = JsonConvert.DeserializeObject<Rootobject>(response);
Console.WriteLine(set.pieces);
}
static async Task askSetNumber()
{
Console.WriteLine("Please enter a setnumber: ");
string setNumber = "{'setNumber':'" + Console.ReadLine().ToString() + "-1'}";
string url = "https://brickset.com/api/v3.asmx/getSets?apiKey=[APIKey here]&userHash=¶ms=" + setNumber;
Console.WriteLine(url);
Program program = new Program();
await program.GetPosts(url);
}
}
I made all classes by Pasting the Json as classes, This is the class of the object I need the data off
public class Rootobject
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public Legocom LEGOCom { get; set; }
public float rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public Agerange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public Extendeddata extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
I tried the example from How to get some values from a JSON string in C#? but set.pieces keeps returning 0.
This is my first time trying this kind of stuff, but I am stuck on this part.
Rootobject does not contain the same information as the json string you outputted to the console (it also escapes square brackets for some reason), so you either need to specify the entire object or navigate the json tree to get the value you require.
This is not a particularly good or robust solution, but you could replace the var set portion of you code with:
JsonDocument doc = JsonDocument.Parse(response);
if (!doc.RootElement.TryGetProperty("sets", out JsonElement sets)) return;
foreach(var set in sets.EnumerateArray())
{
if (!set.TryGetProperty("pieces", out JsonElement pieces)) continue;
Console.WriteLine(pieces.GetInt32());
}
(You'll also need using System.Text.Json; rather than the newtonsoft one.)
you have you json at first,since you have some strange "/" chars, after this you have to fix your classes too
json=json.Replace("\\[","[").Replace("\\]","]");
Set set = JsonConvert.DeserializeObject<Set>(json);
public class Set
{
public string status { get; set; }
public int matches { get; set; }
public List<SetItem> sets { get; set; }
}
public class SetItem
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public LEGOCom LEGOCom { get; set; }
public double rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public AgeRange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public ExtendedData extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
public class LEGOCom
{
public Country US { get; set; }
public Country UK { get; set; }
public Country CA { get; set; }
public Country DE { get; set; }
}
public class AgeRange
{
public int min { get; set; }
}
public class Barcode
{
public string EAN { get; set; }
}
public class Country
{
public double retailPrice { get; set; }
public DateTime dateFirstAvailable { get; set; }
}
and maybe it make some sense to define LEGOCom as a Dictionary, if you have much more countries
public Dictionary<string,Country> LEGOCom { get; set; }
Here are my models:
public class Order
{
public IEnumerable<LineItem> LineItems { get; set; }
}
public class LineItem
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
[JsonPropertyName("variation_id")]
public int VariationId { get; set; }
[JsonPropertyName("quantity")]
public int Quantity { get; set; }
[JsonPropertyName("tax_class")]
public string TaxClass { get; set; }
[JsonPropertyName("subtotal")]
public string Subtotal { get; set; }
[JsonPropertyName("subtotal_tax")]
public string SubtotalTax { get; set; }
[JsonPropertyName("total")]
public string Total { get; set; }
[JsonPropertyName("total_tax")]
public string TotalTax { get; set; }
[JsonPropertyName("taxes")]
public List<object> Taxes { get; set; }
[JsonPropertyName("meta_data")]
public List<MetaData> MetaData { get; set; }
[JsonPropertyName("sku")]
public string Sku { get; set; }
[JsonPropertyName("price")]
public double Price { get; set; }
[JsonPropertyName("parent_name")]
public string ParentName { get; set; }
}
As you can see the HttpRequest property contains an array of line items:
[
{
"id":7928,
"parent_id":0,
"status":"on-hold",
"currency":"GBP",
"version":"5.7.1",
"prices_include_tax":true,
"date_created":"2021-10-04T00:26:22",
"date_modified":"2021-10-04T00:26:22",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"customer_id":3,
"order_key":"redacted",
"billing":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"email":"redacted",
"phone":"redacted"
},
"shipping":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted Lane",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"phone":""
},
"payment_method":"bacs",
"payment_method_title":"Direct bank transfer",
"transaction_id":"",
"customer_ip_address":"redacted",
"customer_user_agent":"redacted",
"created_via":"redacted",
"customer_note":"",
"date_completed":null,
"date_paid":null,
"cart_hash":"redacted",
"number":"redacted",
"meta_data":[
{
"id":190011,
"key":"redacted",
"value":"no"
},
{
"id":190012,
"key":"redacted",
"value":"yes"
},
{
"id":190016,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":190017,
"key":"_thankyou_action_done",
"value":"1"
}
],
"line_items":[
{
"id":5287,
"name":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S",
"product_id":5699,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"2.50",
"subtotal_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48648,
"key":"_WCPA_order_meta_data",
"value":"",
"display_key":"_WCPA_order_meta_data",
"display_value":""
}
],
"sku":"",
"price":2.5,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
{
"id":5288,
"method_title":"Collect from store",
"method_id":"local_pickup",
"instance_id":"13",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48647,
"key":"Items",
"value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1",
"display_key":"Items",
"display_value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1"
}
]
}
],
"fee_lines":[
],
"coupon_lines":[
],
"refunds":[
],
"date_created_gmt":"2021-10-03T23:26:22",
"date_modified_gmt":"2021-10-03T23:26:22",
"date_completed_gmt":null,
"date_paid_gmt":null,
"currency_symbol":"\u00a3",
"_links":{
"self":[
{
"href":"redacted"
}
],
"collection":[
{
"href":"redacted"
}
],
"customer":[
{
"href":"redacted"
}
]
}
},
]
I am wondering why when this is deserialized using
public class WooCommerceOrders
{
private HttpRequestService _httpRequestService;
private string _url;
public WooCommerceOrders()
{
_httpRequestService = new HttpRequestService();
_url = "https://kegthat.com/wp-json/wc/v3/orders";
}
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<List<Order>>(result.Result);
}
}
The json for line items returns
"lineItems": null,
however some fields such as shipping return
"shipping": {
"firstName": null,
"lastName": null,
"company": "",
"address1": null,
"address2": null,
"city": "redacting city",
"state": "Cheshire",
"postcode": "redacting postcode",
"country": "GB",
"phone": ""
},
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
Why can I not return line items?
Try this using Newtonsoft.Json
using Newtonsoft.Json;
.....
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject< List<Order>>(result.Result);
}
test to get line_items
var result= GetOrdersJson();
var lineItems=result[0].line_items;
[
{
"id": 5287,
"name": "John Guest 3/8 to 1/4 Fitting PI0112f4S",
"product_id": 5699,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "2.50",
"subtotal_tax": "0.00",
"total": "2.50",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 48648,
"key": "_WCPA_order_meta_data",
"value": "",
"display_key": "_WCPA_order_meta_data",
"display_value": ""
}
],
"sku": "",
"price": 2.5,
"parent_name": null
}
]
classes
public class Order
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public DateTime date_created { get; set; }
public DateTime date_modified { get; set; }
public string discount_total { get; set; }
public string discount_tax { get; set; }
public string shipping_total { get; set; }
public string shipping_tax { get; set; }
public string cart_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public int customer_id { get; set; }
public string order_key { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public object date_completed { get; set; }
public object date_paid { get; set; }
public string cart_hash { get; set; }
public string number { get; set; }
public List<MetaData> meta_data { get; set; }
public List<LineItem> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
public List<object> refunds { get; set; }
public DateTime date_created_gmt { get; set; }
public DateTime date_modified_gmt { get; set; }
public object date_completed_gmt { get; set; }
public object date_paid_gmt { get; set; }
public string currency_symbol { get; set; }
public Links _links { get; set; }
}
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string phone { get; set; }
}
public class MetaData
{
public int id { get; set; }
public string key { get; set; }
public string value { get; set; }
public string display_key { get; set; }
public string display_value { get; set; }
}
public class LineItem
{
public int id { get; set; }
public string name { get; set; }
public int product_id { get; set; }
public int variation_id { get; set; }
public int quantity { get; set; }
public string tax_class { get; set; }
public string subtotal { get; set; }
public string subtotal_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
public string sku { get; set; }
public double price { get; set; }
public object parent_name { get; set; }
}
public class ShippingLine
{
public int id { get; set; }
public string method_title { get; set; }
public string method_id { get; set; }
public string instance_id { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class Collection
{
public string href { get; set; }
}
public class Customer
{
public string href { get; set; }
}
public class Links
{
public List<Self> self { get; set; }
public List<Collection> collection { get; set; }
public List<Customer> customer { get; set; }
}
IEnumerable<T> is not a valid type for the serializer. It doesn't define any concrete implementation of a collection for the serializer to parse the JSON into. Use List<T> when deserializing JSON arrays.
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<Order>(result.Result);
}
Deserializing List<Order> which is not the Deserializer is expecting.
Try return _httpRequestService.DeserializeApiResponseJson<Order> instead
I created some classes based on the json data in order to deserialize the json data.
I would like to access the sku and the skuName using a lambda expression but i am unable to do so.
So managed to get the skuName, but how do i get sku property? i want to get the skuName property and the associated sku property as well. skuName and sku belong to the same class- SKU class. Thanks for your time
var productSku = skuIdName.BodyText.products.vendors
.SelectMany(x => x.listings
.SelectMany(l => l.skus
.SelectMany(f => f.skuName
))).ToArray();
I am unable to obtain ALL the skus and sdkuName (using lambda) and put it in a list or a dictionary using the sku value as Key and the skuName as the value, as i would later like to store these values in a database.
e.g.
"sku": "SK8772",
"skuName": "Domestic and International Calling Plan",
"sku": "SK8265",
"skuName": "Audio Conferencing",
JSON DATA:
{
"Result": "Success",
"BodyText":
{
"products":
{
"totalProducts": 510,
"recordsPerPage": 10,
"page": 1,
"totalPages": 51,
"vendors": [
{
"vendorId": "397",
"vendorName": "Microsoft",
"listings": [
{
"listingName": "Office 365 Enterprise",
"skus": [
{
"sku": "SK10228",
"skuName": "Microsoft 365 E5 without Audio Conferencing",
"description": "Pending",
"zeroValueSku": "t",
"manufacturerPartNumber": "db5e0b1c9cc3459c9d08c61993959fd3",
"article": "4090153",
"vendorMapId": "db5e0b1c-9cc3-459c-9d08-c61993959fd3",
"billingType": "Monthly",
"productType": "SaaS",
"qtyMin": "1",
"qtyMax": "",
"addOns": [
{
"sku": "SK8265",
"skuName": "Audio Conferencing",
"description": "For businesses that need to enable users to dial-in a number to join Skype meetings, or dial-out to bring participants into the meeting. There are base pre-requisites required to purchase this offering.",
"zeroValueSku": "t",
"qtyMin": "1",
"qtyMax": "",
"vendorMapId": "c94271d8-b431-4a25-a3c5-a57737a1c909",
"manufacturerPartNumber": "c94271d8b4314a25a3c5a57737a1c909",
"article": "3873033"
},
{
"sku": "SK8772",
"skuName": "Domestic and International Calling Plan",
"description": "For Businesses that need to enable online users to place or receive Domestic and International calls through the Public Switched Telephone Network (PSTN). There are base pre-requisites required to purchase this offering.",
"zeroValueSku": "t",
"qtyMin": "1",
"qtyMax": "",
"vendorMapId": "ded34535-507f-4246-8370-f9180318c537",
"manufacturerPartNumber": "ded34535507f42468370f9180318c537",
"article": "3968760"
},
}
]
}
]
}
]
}
]
}
},
"Key": 3298012
}
public class AddOn
{
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public string vendorMapId { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public class Sku
{
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public string vendorMapId { get; set; }
public string billingType { get; set; }
public string productType { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public List<AddOn> addOns { get; set; }
public List<string> datacenterLocations { get; set; }
public List<AddOn2> add { get; set; }
}
public class AddOn2
{
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public List<Sku> sk { get; set; }
}
public class Listing
{
public string listingName { get; set; }
public List<Sku> skus { get; set; }
public List<AddOn2> addOns { get; set; }
//new
//public List<AddOn2> addon2s { get; set; }
}
public class Vendor
{
public string vendorId { get; set; }
public string vendorName { get; set; }//microsoft
public List<Listing> listings { get; set; }
// public List<Sku> skus { get; set; }
}
public class Products
{
public int totalProducts { get; set; }
public int recordsPerPage { get; set; }
public int page { get; set; }
public int totalPages { get; set; }
public List<Vendor> vendors { get; set; }
}
public class BodyText
{
public Products products { get; set; }
}
public class RootObject
{
public string Result { get; set; }
public BodyText BodyText { get; set; }
public int Key { get; set; }
}
}
RootObject skuIdName = JsonConvert.DeserializeObject<RootObject>(jsonStorageProducts);
Not sure you meant this:
void Main()
{
string jsonStorageProducts = #"
{
""Result"": ""Success"",
""BodyText"":
{
""products"":
{
""totalProducts"": 510,
""recordsPerPage"": 10,
""page"": 1,
""totalPages"": 51,
""vendors"": [
{
""vendorId"": ""397"",
""vendorName"": ""Microsoft"",
""listings"": [
{
""listingName"": ""Office 365 Enterprise"",
""skus"": [
{
""sku"": ""SK10228"",
""skuName"": ""Microsoft 365 E5 without Audio Conferencing"",
""description"": ""Pending"",
""zeroValueSku"": ""t"",
""manufacturerPartNumber"": ""db5e0b1c9cc3459c9d08c61993959fd3"",
""article"": ""4090153"",
""vendorMapId"": ""db5e0b1c-9cc3-459c-9d08-c61993959fd3"",
""billingType"": ""Monthly"",
""productType"": ""SaaS"",
""qtyMin"": ""1"",
""qtyMax"": """",
""addOns"": [
{
""sku"": ""SK8265"",
""skuName"": ""Audio Conferencing"",
""description"": ""For businesses that need to enable users to dial-in a number to join Skype meetings, or dial-out to bring participants into the meeting. There are base pre-requisites required to purchase this offering."",
""zeroValueSku"": ""t"",
""qtyMin"": ""1"",
""qtyMax"": """",
""vendorMapId"": ""c94271d8-b431-4a25-a3c5-a57737a1c909"",
""manufacturerPartNumber"": ""c94271d8b4314a25a3c5a57737a1c909"",
""article"": ""3873033""
},
{
""sku"": ""SK8772"",
""skuName"": ""Domestic and International Calling Plan"",
""description"": ""For Businesses that need to enable online users to place or receive Domestic and International calls through the Public Switched Telephone Network (PSTN). There are base pre-requisites required to purchase this offering."",
""zeroValueSku"": ""t"",
""qtyMin"": ""1"",
""qtyMax"": """",
""vendorMapId"": ""ded34535-507f-4246-8370-f9180318c537"",
""manufacturerPartNumber"": ""ded34535507f42468370f9180318c537"",
""article"": ""3968760""
}
]
}
]
}
]
}
]
}
},
""Key"": 3298012
}
";
RootObject skuIdName = JsonConvert.DeserializeObject<RootObject>(jsonStorageProducts);
var productSku = skuIdName.BodyText.products.vendors
.SelectMany(x =>x.listings
.SelectMany(l => l.skus
.SelectMany(s => s.addOns
.Select(o => new {
SKU = o.sku,
Name = o.skuName }))));
foreach (var sku in productSku)
{
Console.WriteLine($"SKU: {sku.SKU}, Name: {sku.Name}");
}
}
public class AddOn
{
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public string vendorMapId { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
public class Sku
{
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public string vendorMapId { get; set; }
public string billingType { get; set; }
public string productType { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public List<AddOn> addOns { get; set; }
public List<string> datacenterLocations { get; set; }
public List<AddOn2> add { get; set; }
}
public class AddOn2
{
public string sku { get; set; }
public string skuName { get; set; }
public string description { get; set; }
public string zeroValueSku { get; set; }
public string qtyMin { get; set; }
public string qtyMax { get; set; }
public string manufacturerPartNumber { get; set; }
public string article { get; set; }
public List<Sku> sk { get; set; }
}
public class Listing
{
public string listingName { get; set; }
public List<Sku> skus { get; set; }
public List<AddOn2> addOns { get; set; }
//new
//public List<AddOn2> addon2s { get; set; }
}
public class Vendor
{
public string vendorId { get; set; }
public string vendorName { get; set; }//microsoft
public List<Listing> listings { get; set; }
// public List<Sku> skus { get; set; }
}
public class Products
{
public int totalProducts { get; set; }
public int recordsPerPage { get; set; }
public int page { get; set; }
public int totalPages { get; set; }
public List<Vendor> vendors { get; set; }
}
public class BodyText
{
public Products products { get; set; }
}
public class RootObject
{
public string Result { get; set; }
public BodyText BodyText { get; set; }
public int Key { get; set; }
}
Output:
SKU: SK8265, Name: Audio Conferencing
SKU: SK8772, Name: Domestic and International Calling Plan
Adding the lambda expression that might help you to take the values you require. Below is an example to get list of SKUs.
var root = new RootObject();
var skus = new List<Sku>();
root.BodyText.products.vendors.ForEach(vendor =>
vendor.listings.ForEach(listing => listing.skus.ForEach(sku => skus.Add(sku))));
The above code will get you the SKUs of all the vendors of all listings and so on. Now using this as an example you should be able to proceed. If you need further help do let me know.
You can use ForEach of LINQ to iterate over the model and populate a dictionary as follows:
var nameIdDict = new Dictionary<string, string>();
skuIdName.BodyText.products.vendors.ForEach(v =>
{
v.Listings.ForEach(listing =>
{
listing.skus.ForEach(s =>
{
nameIdDict.Add(s.sku, s.skuName);
s.addOns.ForEach(a =>
{
nameIdDict.Add(a.sku, a.skuName);
});
s.add.ForEach(a =>
{
nameIdDict.Add(a.sku, a.skuName);
});
});
listing.addOns.ForEach(a =>
{
nameIdDict.Add(a.sku, a.skuName);
});
});
});
Ultimately you should get the sku and respective skuNames in the dictionary. Though you won't be knowing at which level in the json it existed.
I am trying to use GitLab webhook 'Push events' to notify users when there are changes in the file.
According to this GitLab help I should receive this as the request body:
{
"object_kind": "push",
"before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
"after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"ref": "refs/heads/master",
"user_id": 4,
"user_name": "John Smith",
"user_email": "john#example.com",
"project_id": 15,
"repository": {
"name": "Diaspora",
"url": "git#example.com:mike/diasporadiaspora.git",
"description": "",
"homepage": "http://example.com/mike/diaspora",
"git_http_url":"http://example.com/mike/diaspora.git",
"git_ssh_url":"git#example.com:mike/diaspora.git",
"visibility_level":0
},
"commits": [
{
"id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"message": "Update Catalan translation to e38cb41.",
"timestamp": "2011-12-12T14:27:31+02:00",
"url": "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"author": {
"name": "Jordi Mallach",
"email": "jordi#softcatala.org"
}
},
{
"id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"message": "fixed readme",
"timestamp": "2012-01-03T23:36:29+02:00",
"url": "http://example.com/mike/diaspora/commit/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"author": {
"name": "GitLab dev user",
"email": "gitlabdev#dv6700.(none)"
}
}
],
"total_commits_count": 4
}
but my WebAPI method is not resolving this request right, the things I tried are
public async Task Post()
public void Post([FromBody] dynamic value)
public void Post([FromBody] PushEvent value) (strongly typed)
none of the above approaches seems to work, however trying this in ruby as shown in example method does work.
So I suppose this is something that have to do with the way I am using the web API. Any thoughts?
My PushEvent Class looks like this:
public class PushEvent
{
public string name { get; set; }
public string url { get; set; }
public string description { get; set; }
public string homepage { get; set; }
public string git_http_url { get; set; }
public string git_ssh_url { get; set; }
public int visibility_level { get; set; }
public string object_kind { get; set; }
public string before { get; set; }
public string after { get; set; }
public int user_id { get; set; }
public string user_name { get; set; }
public string user_email { get; set; }
public int project_id { get; set; }
public IList<Commit> commits { get; set; }
public int total_commits_count { get; set; }
public class Author
{
public string name { get; set; }
public string email { get; set; }
}
public class Commit
{
public string id { get; set; }
public string message { get; set; }
public DateTime timestamp { get; set; }
public string url { get; set; }
public Author author { get; set; }
}
}
I' ve met the same question,and my problem was caused by PAI code
the following is my code:
pushEvents:
namespace LuckyGitlabStatWebAPI.Models
{
public class PushEvent
{
public string object_kind { get; set; }
public string before { get; set; }
public string after { get; set; }
public string #ref { get; set; }
public int user_id { get; set; }
public string user_name { get; set; }
public string user_email { get; set; }
public string user_avatar { get; set; }
public int project_id { get; set; }
public project project;
public repository repository;
public List<commits> commits;
public int total_commits_count { get; set; }
}
public class project
{
public string name { get; set; }
public string description { get; set; }
public string web_url { get; set; }
public string avatar_url { get; set; }
public string git_ssh_url { get; set; }
public string git_http_url { get; set; }
public string #namespace { get; set; }
public int visibility_level { get; set; }
public string path_with_namespace { get; set; }
public string default_branch { get; set; }
public string homepage { get; set; }
public string url { get; set; }
public string ssh_url { get; set; }
public string http_url { get; set; }
}
public class repository
{
public string name { get; set; }
public string url { get; set; }
public string description { get; set; }
public string homepage { get; set; }
public string git_http_url { get; set; }
public string git_ssh_url { get; set; }
public int visibility_level { get; set; }
}
public class commits
{
public string id { get; set; }
public string message { get; set; }
public string timestamp { get; set; }
public string url { get; set; }
public string added { get; set; }
public Array modified;
public Array removed { get; set; }
public author author;
}
public class author
{
public string name { get; set; }
public string email { get; set; }
}
}
API :how to get push info from gitlab hooks with .NET
I did find what the problem was, This was due to authentication. Once I allow the method to allow anonmymous, the method was successfully hit.
Lets say i have a string that looks like this
{
"_links": {
"next": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=0"
},
"follows": [
{
"created_at": "2013-06-02T09:38:45Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels/test_channel"
},
"channel": {
"banner": null,
"_id": 1,
"url": "http://www.twitch.tv/test_channel",
"mature": null,
"teams": [
],
"status": null,
"logo": null,
"name": "test_channel",
"video_banner": null,
"display_name": "test_channel",
"created_at": "2007-05-22T10:37:47Z",
"delay": 0,
"game": null,
"_links": {
"stream_key": "https://api.twitch.tv/kraken/channels/test_channel/stream_key",
"self": "https://api.twitch.tv/kraken/channels/test_channel",
"videos": "https://api.twitch.tv/kraken/channels/test_channel/videos",
"commercial": "https://api.twitch.tv/kraken/channels/test_channel/commercial",
"chat": "https://api.twitch.tv/kraken/chat/test_channel",
"features": "https://api.twitch.tv/kraken/channels/test_channel/features"
},
"updated_at": "2008-02-12T06:04:29Z",
"background": null
}
},
...
]
}
The part in channel is gonna appear x amount of times with the "name" part having a different value. How would I, using regex or not get the value in "name" that in the code above has a value of "test_channel". All times that it appears and then print it to a textbox
The only part I think I've managed is the regex part
string regex = #"(""name"":)\s+(\w+)(,""video_banner"")";
Using Json.Net and this site
var obj = JsonConvert.DeserializeObject<Krysvac.RootObject>(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
public class Krysvac
{
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
}
If you don't want to declare these classes, you can use dynamic keyword too
dynamic obj = JsonConvert.DeserializeObject(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
If you build classes for your input string like the following using json2csharp.com, you'll get the following classes:
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
Now you just have to deserialize the input json string to RootObject class and fetch all the names in the input string using another utility called Json.net
string json = "JSON STRING";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
List<string> names = root.follows.Select(follow => follow.channel.name).ToList();
foreach ( string name in names )
{
txtBox += name + "; ";
}
Ok, so i got it working now, however, if i use my username to get back json, i get a huge piece of code that you can view here: https://api.twitch.tv/kraken/users/krysvac/follows/channels
I folllow 31 people but when i use my program on it with the code
using (var w = new WebClient())
{
string json_data = w.DownloadString("https://api.twitch.tv/kraken/users/" + input + "/follows/channels");
dynamic obj = JsonConvert.DeserializeObject(json_data);
foreach (var item in obj.follows)
{
textBox1.AppendText(item.channel.name.ToString() + Environment.NewLine);
}
}
i get 25 out of my 31 people back in the textbox and i dont know why, i tried it on a person that should return more than 100 and got 6 people back.