Deserialize json string to C# object in desktop application - c#

{
"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

Related

Deserialize JSON items

I have a function that returns JSON like this:
jsonParsed = {
"account-number": "xxxxxxxx",
"symbol": "XLE 230120C00070000",
"instrument-type": "Equity Option",
"underlying-symbol": "XLE",
"quantity": 3,
"quantity-direction": "Short",
"close-price": "7.64",
"average-open-price": "7.95",
"average-yearly-market-close-price": "7.95",
"average-daily-market-close-price": "7.64",
"multiplier": 100,
"cost-effect": "Debit",
"is-suppressed": false,
"is-frozen": false,
"restricted-quantity": 0,
"expires-at": "2023-01-20T15:15:00-06:00",
"realized-day-gain": "0.0",
"realized-day-gain-effect": "None",
"realized-day-gain-date": "2022-07-05",
"realized-today": "0.0",
"realized-today-effect": "None",
"realized-today-date": "2022-07-05",
"created-at": "xxxx-xx-xxxxx:xx:xx.xxx-xx:00",
"updated-at": "xxxx-xx-xxxxx:xx:xx.xx-xx:00"
}
I am trying to deserialize this to a C# class:
public class PositionResult
{
public string AccountNumber { get; set; }
public string Symbol { get; set; }
public string InstrumentType { get; set; }
public string UnderlyingSymbol { get; set; }
public string Quantity { get; set; }
public string QuantityDirection { get; set; }
public string ClosePrice { get; set; }
public string AverageOpenPrice { get; set; }
public string AverageYearlyMarketClosePrice { get; set; }
public string AverageDailyMarketClosePrice { get; set; }
public string multiplier { get; set; }
public string CostEffect { get; set; }
public string IsSuppressed { get; set; }
public string IsFrozen { get; set; }
public string RestrictedQuantity { get; set; }
public string ExpiresAt { get; set; }
public string RealizedDayGain { get; set; }
public string RealizedDayGainEffect { get; set; }
public string RealizedDayGainDate { get; set; }
public string RealizedToday { get; set; }
public string RealizedTodayEffect { get; set; }
public string RealizedTodayDate { get; set; }
public string CreatedAt { get; set;}
public string UpdatedAt { get; set;}
public override string ToString()
{
return this.ReportAllProperties();
}
}
dataDeSerialized = JsonConvert.DeserializeObject<PositionResult>(jsonParsed, new
JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
However, most of the fiels in dataDeSerialized are null with a few exceptions. I suspect that the "xxxx" : "xxxx" format is the problem, but I am not sure what I am doing wrong?
C# class property names should be the same as json property names.Common way to syncronize them is using [JsonProperty] attribute for Newtonsoft.Json. Try this class
public class PositionResult
{
[JsonProperty("account-number")]
public string AccountNumber { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("instrument-type")]
public string InstrumentType { get; set; }
[JsonProperty("underlying-symbol")]
public string UnderlyingSymbol { get; set; }
[JsonProperty("quantity")]
public long Quantity { get; set; }
[JsonProperty("quantity-direction")]
public string QuantityDirection { get; set; }
[JsonProperty("close-price")]
public string ClosePrice { get; set; }
[JsonProperty("average-open-price")]
public string AverageOpenPrice { get; set; }
[JsonProperty("average-yearly-market-close-price")]
public string AverageYearlyMarketClosePrice { get; set; }
[JsonProperty("average-daily-market-close-price")]
public string AverageDailyMarketClosePrice { get; set; }
[JsonProperty("multiplier")]
public long Multiplier { get; set; }
[JsonProperty("cost-effect")]
public string CostEffect { get; set; }
[JsonProperty("is-suppressed")]
public bool IsSuppressed { get; set; }
[JsonProperty("is-frozen")]
public bool IsFrozen { get; set; }
[JsonProperty("restricted-quantity")]
public long RestrictedQuantity { get; set; }
[JsonProperty("expires-at")]
public DateTimeOffset ExpiresAt { get; set; }
[JsonProperty("realized-day-gain")]
public string RealizedDayGain { get; set; }
[JsonProperty("realized-day-gain-effect")]
public string RealizedDayGainEffect { get; set; }
[JsonProperty("realized-day-gain-date")]
public DateTimeOffset RealizedDayGainDate { get; set; }
[JsonProperty("realized-today")]
public string RealizedToday { get; set; }
[JsonProperty("realized-today-effect")]
public string RealizedTodayEffect { get; set; }
[JsonProperty("realized-today-date")]
public DateTimeOffset RealizedTodayDate { get; set; }
[JsonProperty("created-at")]
public string CreatedAt { get; set; }
[JsonProperty("updated-at")]
public string UpdatedAt { get; set; }
}
Your JSON needs to have the same spelling and capitalization as your class. For example your account number field is "account-number" in your JSON but your class spells it as "AccountNumber". Either change the JSON or change your class so that the field names match, though it would be neater to change the JSON.

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 complex Json using c#

How to deserialize the below JSON using c#
string data = #"{""root"": { ""EmployeeMaster"": { ""EmployeeMasterData"": [ { ""ContactDetails"": { ""ContactDetail"": [ { ""BKPLZ"": ""1"", ""Action"": ""Create"", ""GBDEP"": ""P"", ""PERNR"": ""1"", ""AddressType"": ""Per"", ""BKORT"": ""P,"" }, { ""BKPLZ"": ""262228"", ""Action"": ""Create"", ""GBDEP"": ""p"", ""PERNR"": ""1"", ""AddressType"": ""Res"", ""BKORT"": ""p"" } ] }, ""BankDetails"": { ""BankDetail"": { ""ZBANKGRP"": ""B"", ""EMFTX"": """", ""BANKN"": ""123"", ""Action"": ""Create"", ""PERNR"": ""1"", ""ZZIFSC"": ""123"", ""ZLSCH"": """" } }, ""BasicDetails"": { ""BasicDetail"": { ""ANREX"": ""Mr."", ""GBLND"": ""IND"", ""PLANS"": """", ""FRO"": ""3"", ""Action"": ""Create"", ""BEGDA"": ""2008-04-15"", ""PERNR"": ""1"", ""IO"": ""2"", ""WERKS"": ""Corporate"", ""MASSG"": """", ""KST01"": ""PDLH201"", ""GSBER"": ""CFHO"", ""VORNA"": ""Kapil"", ""ORT01"": ""Noida"", ""NATIO"": ""IND"", ""NACHIN"": ""M"", ""PERSK"": ""MG4"", ""GESCH"": ""Male"", ""PERSG"": ""Active"", ""ABKRS"": ""CM"", ""BTRTAL"": ""N"", ""GBDAT"": ""1980-07-28"", ""RO"": ""2"", ""KBU01"": ""L"" } } } ] } }}";
var json = JObject.Parse(data);
var serializer = new JsonSerializer();
var a= serializer.Deserialize<EmployeeMasterData>(json["root"]["EmployeeMaster"].CreateReader());
public class EmployeeMasterData
{
public List<List<ContactDetail>> ContactDetails { get; set; }
public List<List<BankDetail>> BankDetails { get; set; }
public List<List<BasicDetail>> BasicDetails { get; set; }
}
public class BankDetail
{
public string ZBANKGRP { get; set; }
public string EMFTX { get; set; }
public string BANKN { get; set; }
public string Action { get; set; }
public string PERNR { get; set; }
public string ZZIFSC { get; set; }
public string ZLSCH { get; set; }
}
public class ContactDetail
{
public string BKPLZ { get; set; }
public string Action { get; set; }
public string GBDEP { get; set; }
public string PERNR { get; set; }
public string AddressType { get; set; }
public string BKORT { get; set; }
}
public class BasicDetail
{
public string ANREX { get; set; }
public string GBLND { get; set; }
public string PLANS { get; set; }
public string FRO { get; set; }
public string Action { get; set; }
public string BEGDA { get; set; }
public string PERNR { get; set; }
public string IO { get; set; }
public string WERKS { get; set; }
public string MASSG { get; set; }
public string KST01 { get; set; }
public string GSBER { get; set; }
public string VORNA { get; set; }
public string ORT01 { get; set; }
public string NATIO { get; set; }
public string NACHIN { get; set; }
public string PERSK { get; set; }
public string GESCH { get; set; }
public string PERSG { get; set; }
public string ABKRS { get; set; }
public string BTRTAL { get; set; }
public string GBDAT { get; set; }
public string RO { get; set; }
public string KBU01 { get; set; }
}
If you intend to deserialize entire Json, your class definition needs some changes. For example,
public class ContactDetail
{
public string BKPLZ { get; set; }
public string Action { get; set; }
public string GBDEP { get; set; }
public string PERNR { get; set; }
public string AddressType { get; set; }
public string BKORT { get; set; }
}
public class ContactDetails
{
public List<ContactDetail> ContactDetail { get; set; }
}
public class BankDetail
{
public string ZBANKGRP { get; set; }
public string EMFTX { get; set; }
public string BANKN { get; set; }
public string Action { get; set; }
public string PERNR { get; set; }
public string ZZIFSC { get; set; }
public string ZLSCH { get; set; }
}
public class BankDetails
{
public BankDetail BankDetail { get; set; }
}
public class BasicDetail
{
public string ANREX { get; set; }
public string GBLND { get; set; }
public string PLANS { get; set; }
public string FRO { get; set; }
public string Action { get; set; }
public string BEGDA { get; set; }
public string PERNR { get; set; }
public string IO { get; set; }
public string WERKS { get; set; }
public string MASSG { get; set; }
public string KST01 { get; set; }
public string GSBER { get; set; }
public string VORNA { get; set; }
public string ORT01 { get; set; }
public string NATIO { get; set; }
public string NACHIN { get; set; }
public string PERSK { get; set; }
public string GESCH { get; set; }
public string PERSG { get; set; }
public string ABKRS { get; set; }
public string BTRTAL { get; set; }
public string GBDAT { get; set; }
public string RO { get; set; }
public string KBU01 { get; set; }
}
public class BasicDetails
{
public BasicDetail BasicDetail { get; set; }
}
public class EmployeeMasterData
{
public ContactDetails ContactDetails { get; set; }
public BankDetails BankDetails { get; set; }
public BasicDetails BasicDetails { get; set; }
}
public class EmployeeMaster
{
public List<EmployeeMasterData> EmployeeMasterData { get; set; }
}
public class Root
{
public EmployeeMaster EmployeeMaster { get; set; }
}
public class RootObject
{
public Root root { get; set; }
}
Now you could deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(data);
If you intend to deserialize only a part of it, for example, as seen in the OP, the EmployeeMaster alone, you could do the following
var json = JObject.Parse(data);
var result= JsonConvert.DeserializeObject<EmployeeMaster>(json["root"]["EmployeeMaster"].ToString());

How to fix deserialization in Json with multiple classes <null in object reference>

I am able to deserialise root object but cannot access the underlying classes I receive a null reference exception. I need to extract the fields from the orderitems class.
in the following scenario the derserialization
works great and can extract fields attached to items
var Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(Sresponse.items);
However doesn't work here
var Sresponse = JsonConvert.DeserializeObject<Item>(json);
Console.WriteLine(Sresponse.orderitems);
Error message : System.NullReferenceException: Object reference not set to an instance of an object
please help.
Json String
{
"totalcount": 103952,
"items": [
{
"orderid": 113951,
"email": "",
"namefirst": "",
"namelast": "",
"company": "",
"moneyfinal_net": "95.92",
"moneyfinal_vat": "23.98",
"moneytotal_gross_roundoff": "0.00",
"moneytotal_gross_all": "119.90",
"checkouttypename": "Card",
"deliverytypename": "",
"orderdate": 1554836745,
"orderstateid": 10,
"paymentstateid": 20,
"ordertypeid": 10,
"registerid": "{AD16AEE2-235F-318A-4323-6B63EC2C40E7}",
"warehouseid": 18,
"datereserved": null,
"currencycode": "NOK",
"additionaldata": {
"pos-timezone": "Europe/Oslo",
"pos-staff-externalid": "4654"
},
"orderitems": [
{
"orderitemid": 0,
"orderitemtype": 10,
"productid": 5486,
"productname": "Test",
"sku": "320991800016",
"productattributes": "",
"externalinput": "",
"externalinputtitle": "",
"unitlabel": "ST",
"quantity": 1,
"decimalunitquantity": null,
"moneynetpriceperunit": "63.92",
"moneypriceorg": "0.00",
"vatvalue": 25,
"deliveryinfo": "",
"moneyitemtotal_net": "63.92",
"moneyitemtotal_vat": "15.98",
"voucherid": 0,
"vouchercode": "",
"vouchername": "",
"moneyoriginalprice": "63.92",
"moneydiscountedprice": "0.00",
"moneydiscount": "0.00",
"salestaxes": [],
"additionaldata": {},
"decimalquantitytotal": "1.000",
"moneynetpriceperquantity": "63.92"
},
Classes
public class Orderitem
{
public int orderitemid { get; set; }
public int orderitemtype { get; set; }
public int productid { get; set; }
public string productname { get; set; }
public string sku { get; set; }
public string productattributes { get; set; }
public string externalinput { get; set; }
public string externalinputtitle { get; set; }
public string unitlabel { get; set; }
public int quantity { get; set; }
public object decimalunitquantity { get; set; }
public string moneynetpriceperunit { get; set; }
public string moneypriceorg { get; set; }
public int vatvalue { get; set; }
public string deliveryinfo { get; set; }
public string moneyitemtotal_net { get; set; }
public string moneyitemtotal_vat { get; set; }
public int voucherid { get; set; }
public string vouchercode { get; set; }
public string vouchername { get; set; }
public string moneyoriginalprice { get; set; }
public string moneydiscountedprice { get; set; }
public string moneydiscount { get; set; }
public List<object> salestaxes { get; set; }
public string decimalquantitytotal { get; set; }
public string moneynetpriceperquantity { get; set; }
}
public class Item
{
public int orderid { get; set; }
public string moneyfinal_net { get; set; }
public string checkouttypename { get; set; }
public int orderdate { get; set; }
public int orderstateid { get; set; }
public string registerid { get; set; }
public int warehouseid { get; set; }
public string currencycode { get; set; }
public List<Orderitem> orderitems { get; set; }
public class RootObject
{
public int totalcount { get; set; }
public List<Item> items { get; set; }
}
Firstly, after fixing your JSON string which is incorrectly defined in the question and then using this Model structure in your case:
Note: For parsing Property names with special characters (like -) in your JSON, you can use the JSONProperty attribute as shown below to parse out those properties.
public class Additionaldata
{
[JsonProperty(PropertyName = "pos-timezone")]
public string postimezone { get; set; }
[JsonProperty(PropertyName = "pos-staff-externalid")]
public string posstaffexternalid { get; set; }
}
public class Orderitem
{
public int orderitemid { get; set; }
public int orderitemtype { get; set; }
public int productid { get; set; }
public string productname { get; set; }
public string sku { get; set; }
public string productattributes { get; set; }
public string externalinput { get; set; }
public string externalinputtitle { get; set; }
public string unitlabel { get; set; }
public int quantity { get; set; }
public object decimalunitquantity { get; set; }
public string moneynetpriceperunit { get; set; }
public string moneypriceorg { get; set; }
public int vatvalue { get; set; }
public string deliveryinfo { get; set; }
public string moneyitemtotal_net { get; set; }
public string moneyitemtotal_vat { get; set; }
public int voucherid { get; set; }
public string vouchercode { get; set; }
public string vouchername { get; set; }
public string moneyoriginalprice { get; set; }
public string moneydiscountedprice { get; set; }
public string moneydiscount { get; set; }
public List<object> salestaxes { get; set; }
public Additionaldata additionaldata { get; set; }
public string decimalquantitytotal { get; set; }
public string moneynetpriceperquantity { get; set; }
}
public class Item
{
public int orderid { get; set; }
public string email { get; set; }
public string namefirst { get; set; }
public string namelast { get; set; }
public string company { get; set; }
public string moneyfinal_net { get; set; }
public string moneyfinal_vat { get; set; }
public string moneytotal_gross_roundoff { get; set; }
public string moneytotal_gross_all { get; set; }
public string checkouttypename { get; set; }
public string deliverytypename { get; set; }
public int orderdate { get; set; }
public int orderstateid { get; set; }
public int paymentstateid { get; set; }
public int ordertypeid { get; set; }
public string registerid { get; set; }
public int warehouseid { get; set; }
public object datereserved { get; set; }
public string currencycode { get; set; }
public Additionaldata additionaldata { get; set; }
public List<Orderitem> orderitems { get; set; }
}
public class RootObject
{
public int totalcount { get; set; }
public List<Item> items { get; set; }
}
And finally deserializing it:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json=#"{'totalcount':103952,'items':[{'orderid':113951,'email':'','namefirst':'','namelast':'','company':'','moneyfinal_net':'95.92','moneyfinal_vat':'23.98','moneytotal_gross_roundoff':'0.00','moneytotal_gross_all':'119.90','checkouttypename':'Card','deliverytypename':'','orderdate':1554836745,'orderstateid':10,'paymentstateid':20,'ordertypeid':10,'registerid':'{AD16AEE2-235F-318A-4323-6B63EC2C40E7}','warehouseid':18,'datereserved':null,'currencycode':'NOK','additionaldata':{'pos-timezone':'Europe/Oslo','pos-staff-externalid':'4654'},'orderitems':[{'orderitemid':0,'orderitemtype':10,'productid':5486,'productname':'Test','sku':'320991800016','productattributes':'','externalinput':'','externalinputtitle':'','unitlabel':'ST','quantity':1,'decimalunitquantity':null,'moneynetpriceperunit':'63.92','moneypriceorg':'0.00','vatvalue':25,'deliveryinfo':'','moneyitemtotal_net':'63.92','moneyitemtotal_vat':'15.98','voucherid':0,'vouchercode':'','vouchername':'','moneyoriginalprice':'63.92','moneydiscountedprice':'0.00','moneydiscount':'0.00','salestaxes':[],'additionaldata':{},'decimalquantitytotal':'1.000','moneynetpriceperquantity':'63.92'}]}]}";
var Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(Sresponse.totalcount);
foreach(var result in Sresponse.items)
{
Console.WriteLine(result.moneyfinal_net);
Console.WriteLine(result.additionaldata.postimezone);
foreach(var result1 in result.orderitems)
{
Console.WriteLine(result1.orderitemid);
Console.WriteLine(result1.orderitemtype);
Console.WriteLine(result1.productid);
Console.WriteLine(result1.productname);
Console.WriteLine(result1.sku);
}
}
}
}
Outputs:
103952
95.92
Europe/Oslo
0
10
5486
Test
320991800016
Working Example: https://dotnetfiddle.net/kGXBQ0

GitLab WebHook post-receive with WebAPI

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.

Categories

Resources