GitLab WebHook post-receive with WebAPI - c#

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.

Related

Problems Deserialising a nested object array

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

Deserialize json string to C# object in desktop application

{
"autoRegUUID": null,
"federationId": "nlk:1601014",
"identityProvider": {
"identityProvider": false,
"identityProviderBusinessKey": "TINC",
"identityProviderCode": "TINC",
"identityProviderName": "Prime"
},
"loginName": "nlk",
"primaryTenant": {
"orgAddress": "13034 Ballne Corporate Pla",
"orgCity": "Charlotte",
"orgName": "Prime, Inc.",
"orgState": "NC",
"orgZip": "28277-198",
"primaryOrganization": "NC0",
"tin": null
},
"puid": "rreppsSsAPnPBgt",
"userId": "rrepp",
"userProfile": {
"activeUser": true,
"email": "Neil_Kirk#Prime.com",
"firstName": "Neil",
"internalUser": true,
"jobTitle": "Portfolio Business Analyst",
"lastLogin": "Jul 01, 2020, 15:23:14 PM",
"lastName": "Kirk",
"npi": null,
"workPhone": "+14123995262",
"workPhoneExt": null
}
}
here is class
public class PremierUserDetails
{
public string autoRegUUID { get; set; }
public string federationId { get; set; }
public string loginName { get; set; }
public string puid { get; set; }
public string userId { get; set; }
public List<identityProvider> Providers { get; set; }
public List<primaryTenant> Tenant { get; set; }
public List<userProfile> Profile { get; set; }
}
public class identityProvider
{
public bool identityProviderAuthViaSSO { get; set; }
public string identityProviderBusinessKey { get; set; }
public string identityProviderCode { get; set; }
public string identityProviderName { get; set; }
}
public class primaryTenant
{
public string orgAddress { get; set; }
public string orgCity { get; set; }
public string orgName { get; set; }
public string orgState { get; set; }
public string orgZip { get; set; }
public string primaryOrganization { get; set; }
public string tin { get; set; }
}
public class userProfile
{
public bool activeUser { get; set; }
public string email { get; set; }
public string firstName { get; set; }
public string displayName { get; set; }
public string internalUser { get; set; }
public string jobTitle { get; set; }
public string lastLogin { get; set; }
public string lastName { get; set; }
public string npi { get; set; }
public string workPhone { get; set; }
public string workPhoneExt { get; set; }
}
..
var jsonData = JsonConvert.DeserializeObject<PremierUserDetails>(json);
PremierUserDetails user = new PremierUserDetails();
but the Providers, Tenant and Profile comes as null rest all are populated with value.
Your "child" object(s) ... do-not/does-not seem to be json arrays. (One giveaway is the lack of [] square brackets)
Try:
public class PremierUserDetails
{
public string autoRegUUID { get; set; }
public string federationId { get; set; }
public string loginName { get; set; }
public string puid { get; set; }
public string userId { get; set; }
public identityProvider identityProvider{ get; set; }
public primaryTenant primaryTenant { get; set; }
public userProfile userProfile { get; set; }
}
Now,
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
C# class names are PascalCase, .. so you want to handle your naming conventions differently.
You can see how to do that here:
https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

Deserialize json multiple array

I have been hitting a wall for days with this.
Can someone please tell me how to deserialize this? I can deserialize single json but deserializing an array has got me stumped.
[
{
"msys": {
"message_event": {
"type": "bounce",
"bounce_class": "1",
"campaign_id": "Example Campaign Name",
"customer_id": "1",
"delv_method": "esmtp",
"device_token": "45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a",
"error_code": "554",
"ip_address": "127.0.0.1",
"message_id": "0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e",
"msg_from": "sender#example.com",
"msg_size": "1337",
"num_retries": "2",
"rcpt_meta": {
"customKey": "customValue"
},
"rcpt_tags": [
"male",
"US"
],
"rcpt_to": "recipient#example.com",
"rcpt_type": "cc",
"raw_reason": "MAIL REFUSED - IP (17.99.99.99) is in black list",
"reason": "MAIL REFUSED - IP (a.b.c.d) is in black list",
"routing_domain": "example.com",
"subject": "Summer deals are here!",
"template_id": "templ-1234",
"template_version": "1",
"timestamp": 1427736822,
"transmission_id": "65832150921904138"
}
}
}
]
My classes are defined as:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
In my case this works. You need to tell Newtonsoft.Json what is your destinationt type (array = list):
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
This is a simple complete example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewtonSoftSample
{
class Program
{
static void Main(string[] args)
{
string json =
#"
[
{
""msys"": {
""message_event"": {
""type"": ""bounce"",
""bounce_class"": ""1"",
""campaign_id"": ""Example Campaign Name"",
""customer_id"": ""1"",
""delv_method"": ""esmtp"",
""device_token"": ""45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a"",
""error_code"": ""554"",
""ip_address"": ""127.0.0.1"",
""message_id"": ""0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e"",
""msg_from"": ""sender#example.com"",
""msg_size"": ""1337"",
""num_retries"": ""2"",
""rcpt_meta"": {
""customKey"": ""customValue""
},
""rcpt_tags"": [
""male"",
""US""
],
""rcpt_to"": ""recipient#example.com"",
""rcpt_type"": ""cc"",
""raw_reason"": ""MAIL REFUSED - IP (17.99.99.99) is in black list"",
""reason"": ""MAIL REFUSED - IP (a.b.c.d) is in black list"",
""routing_domain"": ""example.com"",
""subject"": ""Summer deals are here!"",
""template_id"": ""templ-1234"",
""template_version"": ""1"",
""timestamp"": 1427736822,
""transmission_id"": ""65832150921904138""
}
}
}
]
";
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
Console.WriteLine("Done");
Console.ReadLine();
}
}
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
}
You're coming with the wrong approach. You want to be able not to know what fields the json contains but only that it will be a valid json object that can be parsed.
I'd first recommend you to understand what json object really is and what it can be composed from. You can read it here
Next, you can use this as a json parser.
Documentation about the use can be found here.
Try deserializing to a List<Class1>
var list = JsonConvert.DeserializeObject<List<Class1>>(json);
foreach (Message_Event msg in list.Select(c => c.msys.message_event))
{
Console.WriteLine("campaign: " + msg.campaign_id);
Console.WriteLine("from: " + msg.msg_from);
Console.WriteLine("to: " + msg.rcpt_to);
// etc.
}
Fiddle: https://dotnetfiddle.net/Ei0apw
You can use:
public class Msys
{
public List<Message_Event> message_event { get; set; }
}
And initialize your List<> with
System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Message_Event>(json);

Get text in string between text in said string

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.

Json decoding not decoding into complex object

So I have a set of classes:
public class CallQueueRequest
{
public string ACK { get; set; }
public string ERROR { get; set; }
public Agent AGENT { get; set; }
public Skill SKILL { get; set; }
public string TIME { get; set; }
}
public class Agent
{
public string has_result { get; set; }
public List<Agents> agents { get; set; }
}
public class Agents
{
public string display_name { get; set; }
public string time_in_state { get; set; }
public string state { get; set; }
public string callstakentoday { get; set; }
public string avaya_skill_num { get; set; }
}
public class Skill
{
public string has_result { get; set; }
public string num_skills { get; set; }
public List<Skills> skills { get; set; }
}
public class Skills
{
public string display_name { get; set; }
public string avaya_skill_num { get; set; }
public string callsinqueue { get; set; }
public string callstoday { get; set; }
public string abantoday { get; set; }
public string lwt { get; set; }
public string ewt { get; set; }
public string servicelvl { get; set; }
public string avgspeedans { get; set; }
public string talktime { get; set; }
}
And I have this Json:
{
"ACK":"SUCCESS",
"ERROR":null,
"AGENT":{
"has_results":1,
"agents":[
{
"display_name":"John Doe",
"time_in_state":"378",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
},
{
"display_name":"Jane Joe",
"time_in_state":"220",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
}
]
},
"SKILL":{
"has_results":1,
"num_skills":1,
"skills":[
{
"display_name":"QueueName",
"avaya_skill_num":"81",
"callsinqueue":"1",
"callstoday":"29",
"abandtoday":"1",
"lwt":"74",
"ewt":"223",
"servicelvl":"86",
"avgspeedans":"35",
"talktime":"873"
}
]
},
"TIME":1355864270
}
I am using this code:
object qr = JsonConvert.DeserializeObject(jsonString);
This does not seem to be converting from Json to the complex class properly. Can someone assist me with this? I think its just a small mistake.
I was able to find some info on what I'm trying to do. If anyone finds this question, here is the answer

Categories

Resources