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; }
}
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
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)]
I'm having some issues handling a JSON array, Here is what I've tried. I have tried also using <List<jsonResponse.RootObect> and get the same result.
I'm using JSON.NET
C#:
jsonResponse.RootObject deserializedResponse = JsonConvert.DeserializeObject<jsonResponse.RootObject>(Globals.jsonResponse);
CLASS:
namespace QuantumView
{
[JsonObjectAttribute]
class jsonResponse
{
public class TransactionReference
{
public string CustomerContext { get; set; }
}
public class Response
{
public TransactionReference TransactionReference { get; set; }
public string ResponseStatusCode { get; set; }
public string ResponseStatusDescription { get; set; }
}
public class SubscriptionStatus
{
public string Code { get; set; }
public string Description { get; set; }
}
public class StatusType
{
public string Code { get; set; }
public string Description { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string City { get; set; }
public string StateProvinceCode { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class Shipper
{
public string Name { get; set; }
public string ShipperNumber { get; set; }
public Address Address { get; set; }
}
public class Address2
{
public string ConsigneeName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string StateProvinceCode { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class ShipTo
{
public string AttentionName { get; set; }
public string PhoneNumber { get; set; }
public Address2 Address { get; set; }
}
public class ReferenceNumber
{
public string Number { get; set; }
public string Value { get; set; }
}
public class Service
{
public string Code { get; set; }
}
public class Activity
{
public string Date { get; set; }
public string Time { get; set; }
}
public class Dimensions
{
public string Length { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
public class UnitOfMeasurement
{
public string Code { get; set; }
}
public class DimensionalWeight
{
public UnitOfMeasurement UnitOfMeasurement { get; set; }
public string Weight { get; set; }
}
public class PackageWeight
{
public string Weight { get; set; }
}
public class ReferenceNumber2
{
public string Number { get; set; }
public string Value { get; set; }
}
public class PackageServiceOptions
{
public string COD { get; set; }
}
[JsonArray]
public class Package
{
public Activity Activity { get; set; }
public Dimensions Dimensions { get; set; }
public DimensionalWeight DimensionalWeight { get; set; }
public PackageWeight PackageWeight { get; set; }
public string TrackingNumber { get; set; }
public List<ReferenceNumber2> ReferenceNumber { get; set; }
public PackageServiceOptions PackageServiceOptions { get; set; }
}
public class BillToAccount
{
public string Option { get; set; }
public string Number { get; set; }
}
[JsonArray]
public class Manifest
{
public Shipper Shipper { get; set; }
public ShipTo ShipTo { get; set; }
public List<ReferenceNumber> ReferenceNumber { get; set; }
public Service Service { get; set; }
public string PickupDate { get; set; }
public string ScheduledDeliveryDate { get; set; }
public string ScheduledDeliveryTime { get; set; }
public string DocumentsOnly { get; set; }
public Package Package { get; set; }
public string ShipmentChargeType { get; set; }
public BillToAccount BillToAccount { get; set; }
}
public class SubscriptionFile
{
public string FileName { get; set; }
public StatusType StatusType { get; set; }
public List<Manifest> Manifest { get; set; }
public object Origin { get; set; }
}
This is where I'm getting the error..
[JsonArray]
public class SubscriptionEvents
{
public string Name { get; set; }
public string Number { get; set; }
public SubscriptionStatus SubscriptionStatus { get; set; }
public List<SubscriptionFile> SubscriptionFile { get; set; }
}
public class QuantumViewEvents
{
public string SubscriberID { get; set; }
public SubscriptionEvents SubscriptionEvents { get; set; }
}
public class QuantumViewResponse
{
public Response Response { get; set; }
public QuantumViewEvents QuantumViewEvents { get; set; }
public string Bookmark { get; set; }
}
public class RootObject
{
public QuantumViewResponse QuantumViewResponse { get; set; }
}
}
}
The problem was with my class not having the correct properties, it also turns out that the UPS api doesn't send a static type response and it can be different each time.. requiring a new class to deserialize into. I have not found a way to make the class flexible
I am using the following tutorial to parse a JSON document.
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
The JSON document that I am trying to parse can be accessed here:
http://www.visitproject.co.uk/Tweets/Ireland.txt
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic tweets = jss.Deserialize(json, typeof(object)) as dynamic;
foreach (var tweettext in tweets.statuses.text)
{
Console.WriteLine("Tweet: " + tweettext);
}
I am able to perform a watch on tweets.statuses and it does contain a collection of tweets. I would like to get the text value from each tweet. The only thing I can see that is different for the tutorial is that it is an array in JSON and I expect that this is why it is not working. Does anyone have any ideas? Thank you for your help!
You could use LINQ to JSON, like this:
// Parse JSON
JObject o = JObject.Parse(json);
Read LINQ to JSON documentation for details on how to query for the pieces of JSON you want.
You can simply copy paste the code below and get your answer.
This is how i parsed your json data.
I created classes based on your json
public class Metadata
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
public class Url2
{
public string url { get; set; }
public string expanded_url { get; set; }
public string display_url { get; set; }
public List<int> indices { get; set; }
}
public class Url
{
public List<Url2> urls { get; set; }
}
public class Description
{
public List<object> urls { get; set; }
}
public class Entities
{
public Url url { get; set; }
public Description description { get; set; }
}
public class User
{
public int id { get; set; }
public string id_str { get; set; }
public string name { get; set; }
public string screen_name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string url { get; set; }
public Entities entities { get; set; }
public bool #protected { get; set; }
public int followers_count { get; set; }
public int friends_count { get; set; }
public int listed_count { get; set; }
public string created_at { get; set; }
public int favourites_count { get; set; }
public int? utc_offset { get; set; }
public string time_zone { get; set; }
public bool geo_enabled { get; set; }
public bool verified { get; set; }
public int statuses_count { get; set; }
public string lang { get; set; }
public bool contributors_enabled { get; set; }
public bool is_translator { get; set; }
public string profile_background_color { get; set; }
public string profile_background_image_url { get; set; }
public string profile_background_image_url_https { get; set; }
public bool profile_background_tile { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string profile_link_color { get; set; }
public string profile_sidebar_border_color { get; set; }
public string profile_sidebar_fill_color { get; set; }
public string profile_text_color { get; set; }
public bool profile_use_background_image { get; set; }
public bool default_profile { get; set; }
public bool default_profile_image { get; set; }
public bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
public string profile_banner_url { get; set; }
}
public class Large
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Medium2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes
{
public Large large { get; set; }
public Medium2 medium { get; set; }
public Thumb thumb { get; set; }
public Small small { get; set; }
}
public class Medium
{
public object id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes sizes { get; set; }
public long source_status_id { get; set; }
public string source_status_id_str { get; set; }
}
public class Entities2
{
public List<object> hashtags { get; set; }
public List<object> symbols { get; set; }
public List<object> urls { get; set; }
public List<object> user_mentions { get; set; }
public List<Medium> media { get; set; }
}
public class Metadata2
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
public class Description2
{
public List<object> urls { get; set; }
}
public class Url4
{
public string url { get; set; }
public string expanded_url { get; set; }
public string display_url { get; set; }
public List<int> indices { get; set; }
}
public class Url3
{
public List<Url4> urls { get; set; }
}
public class Entities3
{
public Description2 description { get; set; }
public Url3 url { get; set; }
}
public class User2
{
public int id { get; set; }
public string id_str { get; set; }
public string name { get; set; }
public string screen_name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string url { get; set; }
public Entities3 entities { get; set; }
public bool #protected { get; set; }
public int followers_count { get; set; }
public int friends_count { get; set; }
public int listed_count { get; set; }
public string created_at { get; set; }
public int favourites_count { get; set; }
public int utc_offset { get; set; }
public string time_zone { get; set; }
public bool geo_enabled { get; set; }
public bool verified { get; set; }
public int statuses_count { get; set; }
public string lang { get; set; }
public bool contributors_enabled { get; set; }
public bool is_translator { get; set; }
public string profile_background_color { get; set; }
public string profile_background_image_url { get; set; }
public string profile_background_image_url_https { get; set; }
public bool profile_background_tile { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string profile_banner_url { get; set; }
public string profile_link_color { get; set; }
public string profile_sidebar_border_color { get; set; }
public string profile_sidebar_fill_color { get; set; }
public string profile_text_color { get; set; }
public bool profile_use_background_image { get; set; }
public bool default_profile { get; set; }
public bool default_profile_image { get; set; }
public bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
}
public class Medium4
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Large2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes2
{
public Medium4 medium { get; set; }
public Large2 large { get; set; }
public Thumb2 thumb { get; set; }
public Small2 small { get; set; }
}
public class Medium3
{
public long id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes2 sizes { get; set; }
}
public class Entities4
{
public List<object> hashtags { get; set; }
public List<object> symbols { get; set; }
public List<object> urls { get; set; }
public List<object> user_mentions { get; set; }
public List<Medium3> media { get; set; }
}
public class RetweetedStatus
{
public Metadata2 metadata { get; set; }
public string created_at { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
public bool truncated { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string in_reply_to_screen_name { get; set; }
public User2 user { get; set; }
public object geo { get; set; }
public object coordinates { get; set; }
public object place { get; set; }
public object contributors { get; set; }
public int retweet_count { get; set; }
public int favorite_count { get; set; }
public Entities4 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public bool possibly_sensitive { get; set; }
public string lang { get; set; }
}
public class Status
{
public Metadata metadata { get; set; }
public string created_at { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
public bool truncated { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string in_reply_to_screen_name { get; set; }
public User user { get; set; }
public object geo { get; set; }
public object coordinates { get; set; }
public object place { get; set; }
public object contributors { get; set; }
public int retweet_count { get; set; }
public int favorite_count { get; set; }
public Entities2 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public bool possibly_sensitive { get; set; }
public string lang { get; set; }
public RetweetedStatus retweeted_status { get; set; }
}
public class SearchMetadata
{
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_results { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public int count { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
public class RootObject
{
public List<Status> statuses { get; set; }
public SearchMetadata search_metadata { get; set; }
}
And i parsed your data by using the following method
public void PARSEVALUES(string jsonValue)//jsonValue contains your json
{
JavaScriptSerializer jss = new JavaScriptSerializer();
RootObject r = jss.Deserialize<RootObject>(jsonValue);
foreach (var tweetText in r.statuses)
{
string val = tweetText.text;
}
}