Deserialize JSON items - c#

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.

Related

Deserializing JSON object says Input string is not a valid integer

i have this Json
{
"queryresult":{
"responseMessage":"success",
"customer":{
"accountNumber":"8292829222",
"meterNumber":"",
"phoneNumber":"",
"lastName":"CHRISTIAN ",
"address":"2 OSISIOMA NGWA, ABIA",
"city":null,
"district":"Damata",
"userCategory":"NON-MD",
"customerType":"unmetered",
"paymentPlan":"Postpaid",
"vat":463.8525,
"tariffCode":"R2SC-NMD",
"tariffRate":53.78,
"arrearsBalance":129324.8435,
"billedAmount":6184.7,
"billedDate":"08-2022",
"lastPayDate":null,
"lastpayment":{
}
},
"responseCode":200,
"status":"true"
},
"status":true
}
When i deserialize with
var data = JsonConvert.DeserializeObject<Data>(readTask);
it throws and error saying
Input String '463.8525' is not a valid integer
which is the vat field
How do i solve this issue? below is my model
public class customer
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public object city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public double vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public double? arrearsBalance { get; set; }
public double billedAmount { get; set; }
public string? billedDate { get; set; }
public string? lastPayDate { get; set; }
public Lastpayments lastpayment { get; set; }
}
public class Lastpayments
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int? amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresults
{
public string responseMessage { get; set; }
public customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Data
{
public Queryresults queryresult { get; set; }
public bool status { get; set; }
}
The error points to the vat field. I tried using [JsonIgnore] to Ignore the vat field as i dont really need it but it dint work

Deserialized Json object value is null

I'm not able to get the value from OneDay.price_change. The HTTP response is OK and I'm getting the following:
HTTP Response
"[{\"id\":\"BTC\",\"currency\":\"BTC\",\"symbol\":\"BTC\",\"name\":\"Bitcoin\",\"logo_url\":\"https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg\",\"status\":\"active\",\"price\":\"60947.08258854\",\"price_date\":\"2021-10-31T00:00:00Z\",\"price_timestamp\":\"2021-10-31T18:51:00Z\",\"circulating_supply\":\"18860037\",\"max_supply\":\"21000000\",\"market_cap\":\"1149464232662\",\"market_cap_dominance\":\"0.4078\",\"num_exchanges\":\"397\",\"num_pairs\":\"67587\",\"num_pairs_unmapped\":\"5196\",\"first_candle\":\"2011-08-18T00:00:00Z\",\"first_trade\":\"2011-08-18T00:00:00Z\",\"first_order_book\":\"2017-01-06T00:00:00Z\",\"rank\":\"1\",\"high\":\"66082.82561618\",\"high_timestamp\":\"2021-10-20T00:00:00Z\",\"1h\":{\"volume\":\"1248590564.91\",\"price_change\":\"-85.32656234\",\"price_change_pct\":\"-0.0014\",\"volume_change\":\"-218879322.04\",\"volume_change_pct\":\"-0.1492\",\"market_cap_change\":\"-1607003923.65\",\"market_cap_change_pct\":\"-0.0014\"},\"1d\":{\"volume\":\"39937857069.60\",\"price_change\":\"-845.68642611\",\"price_change_pct\":\"-0.0137\",\"volume_change\":\"1918883279.43\",\"volume_change_pct\":\"0.0505\",\"market_cap_change\":\"-15892518975.54\",\"market_cap_change_pct\":\"-0.0136\"}}]\n"
However, for some reason, I'm not able to take the 1d price change. I'm not sure what could be the problem. Any help is appreciated!
Model:
public class OneHour
{
public string Volume { get; set; }
public string Price_change { get; set; }
public string Price_change_pct { get; set; }
public string Volume_change { get; set; }
public string Volume_change_pct { get; set; }
public string Market_cap_change { get; set; }
public string Market_cap_change_pct { get; set; }
}
public class OneDay
{
public string Volume { get; set; }
public string Price_change { get; set; }
public string Price_change_pct { get; set; }
public string Volume_change { get; set; }
public string Volume_change_pct { get; set; }
public string Market_cap_change { get; set; }
public string Market_cap_change_pct { get; set; }
}
public class CryptoApiMain
{
public OneHour OneHour { get; set; }
public OneDay OneDay { get; set; }
public string Id { get; set; }
public string Symbol { get; set; }
public string Status { get; set; }
public double Price { get; set; }
public string Price_date { get; set; }
public string Circulating_supply { get; set; }
public string Num_exchanges { get; set; }
public string Num_pairs { get; set; }
public string Rank { get; set; }
public string High { get; set; }
}
var theresponse = settingsService.CryptoApiResult(cryptoStock).Result;
foreach (var rez in theresponse)
{
<span id="stockSymbolCrypto">#cryptoStock</span>
<p>$#Convert.ToInt64(#rez.Price) #rez.OneDay.Price_change</p>
}
#rez.OneDay.Price_change error popup
Problem is that your property name in json (1d) and property name in c# model (OneDay) is not matching.
Use the below if you are using System.Text.Json (.Net Core 3.0 and newer)
[JsonPropertyName("1d")]
public OneDay OneDay { get; set; }
Use the below if you are using Newtonsoft (Before .Net Core 3.0)
[JsonProperty(PropertyName = "1d")]
public OneDay OneDay { get; set; }
Your " public OneHour OneHour { get; set; } " and " public OneDay OneDay { get; set; } " properties should be bind to [JsonProperty("1h")] and [JsonProperty("1d")]
try this
CryptoApiMain[] jsond = JsonConvert.DeserializeObject<CryptoApiMain[]>(json);
var price = jsond[0].OneDay.PriceChange;
result
-845.68642611
classes
public partial class CryptoApiMain
{
[JsonProperty("1h")]
public One OneHour { get; set; }
[JsonProperty("1d")]
public One OneDay { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("logo_url")]
public Uri LogoUrl { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
[JsonProperty("price_date")]
public DateTimeOffset PriceDate { get; set; }
[JsonProperty("price_timestamp")]
public DateTimeOffset PriceTimestamp { get; set; }
[JsonProperty("circulating_supply")]
public long CirculatingSupply { get; set; }
[JsonProperty("max_supply")]
public long MaxSupply { get; set; }
[JsonProperty("market_cap")]
public string MarketCap { get; set; }
[JsonProperty("market_cap_dominance")]
public string MarketCapDominance { get; set; }
[JsonProperty("num_exchanges")]
public long NumExchanges { get; set; }
[JsonProperty("num_pairs")]
public long NumPairs { get; set; }
[JsonProperty("num_pairs_unmapped")]
public long NumPairsUnmapped { get; set; }
[JsonProperty("first_candle")]
public DateTimeOffset FirstCandle { get; set; }
[JsonProperty("first_trade")]
public DateTimeOffset FirstTrade { get; set; }
[JsonProperty("first_order_book")]
public DateTimeOffset FirstOrderBook { get; set; }
[JsonProperty("rank")]
public long Rank { get; set; }
[JsonProperty("high")]
public string High { get; set; }
[JsonProperty("high_timestamp")]
public DateTimeOffset HighTimestamp { get; set; }
}
public partial class One
{
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("price_change")]
public string PriceChange { get; set; }
[JsonProperty("price_change_pct")]
public string PriceChangePct { get; set; }
[JsonProperty("volume_change")]
public string VolumeChange { get; set; }
[JsonProperty("volume_change_pct")]
public string VolumeChangePct { get; set; }
[JsonProperty("market_cap_change")]
public string MarketCapChange { get; set; }
[JsonProperty("market_cap_change_pct")]
public string MarketCapChangePct { get; set; }
}

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

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

Not getting all node value of XML

I have a XML from that i want to get all node value. But after Deserialize i am getting null in my order node and inner node, can you please tell me what mistake I am doing.
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<Order Notes="Test Order" PackageTypeID="0" Service="Quote" CallerPhone="" CustomerCode="GA" Caller="" CalledBy="" CheckPiecesWeight="Y" ForceReRateFlag="True" RouteNumber="" OrderDate="08/04/2017" Auth="" Requestor="CVS - Lenexa" UserGUID="{788888-4555-4444-5455-55555}" GetUserGUIDDataCalledBy="Oreser" WebUserID="254282" UserName="TREW" ChangeOps="0" OrderID="1803019" OrderGUID="{6454546-ABD0-91CA-841D75A363CB}" Origin="W" OrderNumber="2718140" OrderDateTime="08/04/2017 10:00" CreateDate="08/09/17 00:31" DimWeightFactor="0" Pieces="1" Weight="0" RouteZone="LAX" CustomerGroup="" ServiceID="0" TotalMiles="0" AmountCharged="$0.00" DriverPayXML="1" CarrierTypeID="1" DueDateTime="8/4/2017 10:00:00 AM" PickedUpDateTime="" DeliveredDateTime="" OperationalStatus="N" saveorderpieceactionstatus="0" AmountChargedChanged="True">
<Stops>
<Stop Sequence="1" StopType="P" Note="" Name="UPS" Address="Adreena St" City="Vansrn NIRC" State="CA" Zip="98741" Phone="" EarlyDateTime="" ScheduledDateTime="8/4/2017 10:00:00 AM" LateDateTime="" AVSQuality="1" Latitude="74.213827" Longitude="-418.481529" DispatchZoneFound="True" Pieces="1" Weight="0">
<OrderStopPieces>
<OrderStopPiece Sequence="1" PieceAction="P" PieceID="714" OrderStopPieceID="1444"/>
</OrderStopPieces>
</Stop>
<Stop Sequence="2" StopType="D" Note="" Name="CCR Nicla" Address="S.BOSE STREET" City="ARI GUTS" State="CA" Zip="94125" Phone="1 (800) 360-0520" EarlyDateTime="" ScheduledDateTime="8/4/2017 10:00:00 AM" LateDateTime="" AVSQuality="1" Latitude="24.201719" Longitude="-17.491973" DispatchZoneFound="True" Pieces="0" Weight="0">
<OrderStopPieces>
<OrderStopPiece Sequence="1" PieceAction="D" PieceID="714" OrderStopPieceID="144"/>
</OrderStopPieces>
</Stop>
</Stops>
<Pieces>
<Piece Sequence="1" Pieces="1" Weight="" Description="" ContainerReference="" Reference="1111" PieceID="1111"/>
</Pieces>
<OrderEvents>
<OrderEvent EventType="MYOrder" Note="Test" Add="True" EventDateTime="8/9/2017 12:31:08 AM" UserName="MMPIO"/>
<OrderEvent EventType="New" Note="" EventDateTime="8/9/2017 12:21:08 AM" UserName="MMPIO"/>
</OrderEvents>
<Site SiteID="13" CompanyID="1008" SiteCode="MMM" SiteType="C" Name="FOO" DBAName="KMI" Address="JHHHH" City="ARIZoNA" State="AR" Zip="125487" Message=" MUT" ARAccountNumber="15470" ARDeptNumber="741" APAccountNumber="14720" APDeptNumber="1" BankAccountNumber="5001" BankDeptNumber="1" DispatchNote="" PaymentGatewayID="0" MName="" MAddress="" MCity="" MState="" MZip="" LogoImageID="0" SiteStatus="C"/>
<OrderFees>
<OrderFee FeeTitle="TS" FeeCode="VS"/>
<OrderFee FeeTitle="WEEE DDEA" FeeCode="QE"/>
</OrderFees>
<OrderNotifies/>
</Order>
</SOAP:Body>
Class for Deserialize
[XmlRoot(ElementName="OrderStopPiece")]
public class OrderStopPiece {
[XmlAttribute(AttributeName="Sequence")]
public string Sequence { get; set; }
[XmlAttribute(AttributeName="PieceAction")]
public string PieceAction { get; set; }
[XmlAttribute(AttributeName="PieceID")]
public string PieceID { get; set; }
[XmlAttribute(AttributeName="OrderStopPieceID")]
public string OrderStopPieceID { get; set; }
}
[XmlRoot(ElementName="OrderStopPieces")]
public class OrderStopPieces {
[XmlElement(ElementName="OrderStopPiece")]
public OrderStopPiece OrderStopPiece { get; set; }
}
[XmlRoot(ElementName="Stop")]
public class Stop {
[XmlElement(ElementName="OrderStopPieces")]
public OrderStopPieces OrderStopPieces { get; set; }
[XmlAttribute(AttributeName="Sequence")]
public string Sequence { get; set; }
[XmlAttribute(AttributeName="StopType")]
public string StopType { get; set; }
[XmlAttribute(AttributeName="Note")]
public string Note { get; set; }
[XmlAttribute(AttributeName="Name")]
public string Name { get; set; }
[XmlAttribute(AttributeName="Address")]
public string Address { get; set; }
[XmlAttribute(AttributeName="City")]
public string City { get; set; }
[XmlAttribute(AttributeName="State")]
public string State { get; set; }
[XmlAttribute(AttributeName="Zip")]
public string Zip { get; set; }
[XmlAttribute(AttributeName="Phone")]
public string Phone { get; set; }
[XmlAttribute(AttributeName="EarlyDateTime")]
public string EarlyDateTime { get; set; }
[XmlAttribute(AttributeName="ScheduledDateTime")]
public string ScheduledDateTime { get; set; }
[XmlAttribute(AttributeName="LateDateTime")]
public string LateDateTime { get; set; }
[XmlAttribute(AttributeName="AVSQuality")]
public string AVSQuality { get; set; }
[XmlAttribute(AttributeName="Latitude")]
public string Latitude { get; set; }
[XmlAttribute(AttributeName="Longitude")]
public string Longitude { get; set; }
[XmlAttribute(AttributeName="DispatchZoneFound")]
public string DispatchZoneFound { get; set; }
[XmlAttribute(AttributeName="Pieces")]
public string Pieces { get; set; }
[XmlAttribute(AttributeName="Weight")]
public string Weight { get; set; }
}
[XmlRoot(ElementName="Stops")]
public class Stops {
[XmlElement(ElementName="Stop")]
public List<Stop> Stop { get; set; }
}
[XmlRoot(ElementName="Piece")]
public class Piece {
[XmlAttribute(AttributeName="Sequence")]
public string Sequence { get; set; }
[XmlAttribute(AttributeName="Pieces")]
public string Pieces { get; set; }
[XmlAttribute(AttributeName="Weight")]
public string Weight { get; set; }
[XmlAttribute(AttributeName="Description")]
public string Description { get; set; }
[XmlAttribute(AttributeName="ContainerReference")]
public string ContainerReference { get; set; }
[XmlAttribute(AttributeName="Reference")]
public string Reference { get; set; }
[XmlAttribute(AttributeName="PieceID")]
public string PieceID { get; set; }
}
[XmlRoot(ElementName="Pieces")]
public class Pieces {
[XmlElement(ElementName="Piece")]
public Piece Piece { get; set; }
}
[XmlRoot(ElementName="OrderEvent")]
public class OrderEvent {
[XmlAttribute(AttributeName="EventType")]
public string EventType { get; set; }
[XmlAttribute(AttributeName="Note")]
public string Note { get; set; }
[XmlAttribute(AttributeName="Add")]
public string Add { get; set; }
[XmlAttribute(AttributeName="EventDateTime")]
public string EventDateTime { get; set; }
[XmlAttribute(AttributeName="UserName")]
public string UserName { get; set; }
}
[XmlRoot(ElementName="OrderEvents")]
public class OrderEvents {
[XmlElement(ElementName="OrderEvent")]
public List<OrderEvent> OrderEvent { get; set; }
}
[XmlRoot(ElementName="Site")]
public class Site {
[XmlAttribute(AttributeName="SiteID")]
public string SiteID { get; set; }
[XmlAttribute(AttributeName="CompanyID")]
public string CompanyID { get; set; }
[XmlAttribute(AttributeName="SiteCode")]
public string SiteCode { get; set; }
[XmlAttribute(AttributeName="SiteType")]
public string SiteType { get; set; }
[XmlAttribute(AttributeName="Name")]
public string Name { get; set; }
[XmlAttribute(AttributeName="DBAName")]
public string DBAName { get; set; }
[XmlAttribute(AttributeName="Address")]
public string Address { get; set; }
[XmlAttribute(AttributeName="City")]
public string City { get; set; }
[XmlAttribute(AttributeName="State")]
public string State { get; set; }
[XmlAttribute(AttributeName="Zip")]
public string Zip { get; set; }
[XmlAttribute(AttributeName="Message")]
public string Message { get; set; }
[XmlAttribute(AttributeName="ARAccountNumber")]
public string ARAccountNumber { get; set; }
[XmlAttribute(AttributeName="ARDeptNumber")]
public string ARDeptNumber { get; set; }
[XmlAttribute(AttributeName="APAccountNumber")]
public string APAccountNumber { get; set; }
[XmlAttribute(AttributeName="APDeptNumber")]
public string APDeptNumber { get; set; }
[XmlAttribute(AttributeName="BankAccountNumber")]
public string BankAccountNumber { get; set; }
[XmlAttribute(AttributeName="BankDeptNumber")]
public string BankDeptNumber { get; set; }
[XmlAttribute(AttributeName="DispatchNote")]
public string DispatchNote { get; set; }
[XmlAttribute(AttributeName="PaymentGatewayID")]
public string PaymentGatewayID { get; set; }
[XmlAttribute(AttributeName="MName")]
public string MName { get; set; }
[XmlAttribute(AttributeName="MAddress")]
public string MAddress { get; set; }
[XmlAttribute(AttributeName="MCity")]
public string MCity { get; set; }
[XmlAttribute(AttributeName="MState")]
public string MState { get; set; }
[XmlAttribute(AttributeName="MZip")]
public string MZip { get; set; }
[XmlAttribute(AttributeName="LogoImageID")]
public string LogoImageID { get; set; }
[XmlAttribute(AttributeName="SiteStatus")]
public string SiteStatus { get; set; }
}
[XmlRoot(ElementName="OrderFee")]
public class OrderFee {
[XmlAttribute(AttributeName="FeeTitle")]
public string FeeTitle { get; set; }
[XmlAttribute(AttributeName="FeeCode")]
public string FeeCode { get; set; }
}
[XmlRoot(ElementName="OrderFees")]
public class OrderFees {
[XmlElement(ElementName="OrderFee")]
public List<OrderFee> OrderFee { get; set; }
}
[XmlRoot(ElementName="Order")]
public class Order {
[XmlElement(ElementName="Stops")]
public Stops Stops { get; set; }
[XmlElement(ElementName="Pieces")]
public Pieces Pieces { get; set; }
[XmlAttribute(AttributeName="Pieces")]
public string _Pieces { get; set; }
[XmlElement(ElementName="OrderEvents")]
public OrderEvents OrderEvents { get; set; }
[XmlElement(ElementName="Site")]
public Site Site { get; set; }
[XmlElement(ElementName="OrderFees")]
public OrderFees OrderFees { get; set; }
[XmlElement(ElementName="OrderNotifies")]
public string OrderNotifies { get; set; }
[XmlAttribute(AttributeName="Notes")]
public string Notes { get; set; }
[XmlAttribute(AttributeName="PackageTypeID")]
public string PackageTypeID { get; set; }
[XmlAttribute(AttributeName="Service")]
public string Service { get; set; }
[XmlAttribute(AttributeName="CallerPhone")]
public string CallerPhone { get; set; }
[XmlAttribute(AttributeName="CustomerCode")]
public string CustomerCode { get; set; }
[XmlAttribute(AttributeName="Caller")]
public string Caller { get; set; }
[XmlAttribute(AttributeName="CalledBy")]
public string CalledBy { get; set; }
[XmlAttribute(AttributeName="CheckPiecesWeight")]
public string CheckPiecesWeight { get; set; }
[XmlAttribute(AttributeName="ForceReRateFlag")]
public string ForceReRateFlag { get; set; }
[XmlAttribute(AttributeName="RouteNumber")]
public string RouteNumber { get; set; }
[XmlAttribute(AttributeName="OrderDate")]
public string OrderDate { get; set; }
[XmlAttribute(AttributeName="Auth")]
public string Auth { get; set; }
[XmlAttribute(AttributeName="Requestor")]
public string Requestor { get; set; }
[XmlAttribute(AttributeName="UserGUID")]
public string UserGUID { get; set; }
[XmlAttribute(AttributeName="GetUserGUIDDataCalledBy")]
public string GetUserGUIDDataCalledBy { get; set; }
[XmlAttribute(AttributeName="WebUserID")]
public string WebUserID { get; set; }
[XmlAttribute(AttributeName="UserName")]
public string UserName { get; set; }
[XmlAttribute(AttributeName="ChangeOps")]
public string ChangeOps { get; set; }
[XmlAttribute(AttributeName="OrderID")]
public string OrderID { get; set; }
[XmlAttribute(AttributeName="OrderGUID")]
public string OrderGUID { get; set; }
[XmlAttribute(AttributeName="Origin")]
public string Origin { get; set; }
[XmlAttribute(AttributeName="OrderNumber")]
public string OrderNumber { get; set; }
[XmlAttribute(AttributeName="OrderDateTime")]
public string OrderDateTime { get; set; }
[XmlAttribute(AttributeName="CreateDate")]
public string CreateDate { get; set; }
[XmlAttribute(AttributeName="DimWeightFactor")]
public string DimWeightFactor { get; set; }
[XmlAttribute(AttributeName="Weight")]
public string Weight { get; set; }
[XmlAttribute(AttributeName="RouteZone")]
public string RouteZone { get; set; }
[XmlAttribute(AttributeName="CustomerGroup")]
public string CustomerGroup { get; set; }
[XmlAttribute(AttributeName="ServiceID")]
public string ServiceID { get; set; }
[XmlAttribute(AttributeName="TotalMiles")]
public string TotalMiles { get; set; }
[XmlAttribute(AttributeName="AmountCharged")]
public string AmountCharged { get; set; }
[XmlAttribute(AttributeName="DriverPayXML")]
public string DriverPayXML { get; set; }
[XmlAttribute(AttributeName="CarrierTypeID")]
public string CarrierTypeID { get; set; }
[XmlAttribute(AttributeName="DueDateTime")]
public string DueDateTime { get; set; }
[XmlAttribute(AttributeName="PickedUpDateTime")]
public string PickedUpDateTime { get; set; }
[XmlAttribute(AttributeName="DeliveredDateTime")]
public string DeliveredDateTime { get; set; }
[XmlAttribute(AttributeName="OperationalStatus")]
public string OperationalStatus { get; set; }
[XmlAttribute(AttributeName="saveorderpieceactionstatus")]
public string Saveorderpieceactionstatus { get; set; }
[XmlAttribute(AttributeName="AmountChargedChanged")]
public string AmountChargedChanged { get; set; }
}
[XmlRoot(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public class Body {
[XmlElement(ElementName="Order")]
public Order Order { get; set; }
}
[XmlRoot(ElementName="Envelope", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope {
[XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName="SOAP", Namespace="http://www.w3.org/2000/xmlns/")]
public string SOAP { get; set; }
}
my code :
// response xml in str
XmlSerializer serializer = new XmlSerializer(typeof(SaveResponseObject.Envelope));
using (TextReader reader = new StringReader(str))
{
SaveResponseObject.Envelope result = (SaveResponseObject.Envelope)serializer.Deserialize(reader);
}
Add Namespace = "" to Order property in Body class. Should be ok.
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "Order", Namespace = "")]
public Order Order { get; set; }
}
Use this attribute to decorate over order
[XmlElement(ElementName = "Order", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

Categories

Resources