How to read all ExportHeaderType node value from below xml file.
<ArrayOfCEDataFileMappingSaveProp xmlns="http://schemas.datacontract.org/2004/07/Test.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<CEDataFileMappingSaveProp>
<HeaderTypes>
<ExportHeaderType>
<AppType>LBX</AppType>
<DocType>Batch</DocType>
<HeaderType>Detail</HeaderType>
<CheckboxField>true</CheckboxField>
<DataFileMapPK>4</DataFileMapPK>
<IsHeaderRequired>false</IsHeaderRequired>
<IsHeaderTypeMandatory>true</IsHeaderTypeMandatory>
<Sequence>0</Sequence>
</ExportHeaderType>
</HeaderTypes>
<DocAppTypeId>LBX</DocAppTypeId>
<DocTypeId>Batch</DocTypeId>
<IsHeadingAvailable>false</IsHeadingAvailable>
</CEDataFileMappingSaveProp>
<CEDataFileMappingSaveProp>
<HeaderTypes>
<ExportHeaderType>
<AppType>LBX</AppType>
<DocType>Check</DocType>
<HeaderType>Detail</HeaderType>
<CheckboxField>true</CheckboxField>
<DataFileMapPK>4</DataFileMapPK>
<IsHeaderRequired>false</IsHeaderRequired>
<IsHeaderTypeMandatory>true</IsHeaderTypeMandatory>
<Sequence>0</Sequence>
</ExportHeaderType>
</HeaderTypes>
<DocAppTypeId>LBX</DocAppTypeId>
<DocTypeId>Check</DocTypeId>
<IsHeadingAvailable>false</IsHeadingAvailable>
</CEDataFileMappingSaveProp>
</ArrayOfCEDataFileMappingSaveProp>
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCEDataFileMappingSaveProp));
ArrayOfCEDataFileMappingSaveProp array = (ArrayOfCEDataFileMappingSaveProp)serializer.Deserialize(reader);
}
}
[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public class ArrayOfCEDataFileMappingSaveProp
{
[XmlElement("CEDataFileMappingSaveProp")]
public List<CEDataFileMappingSaveProp> saveProp { get; set; }
}
public class CEDataFileMappingSaveProp
{
public string DocAppTypeId { get; set; }
public string DocTypeId { get; set; }
public Boolean IsHeadingAvailable { get; set; }
[XmlArray("HeaderTypes")]
[XmlArrayItem("ExportHeaderType")]
public List<HeaderTypes> headers { get; set; }
}
public class HeaderTypes
{
public string AppType { get; set; }
public string DocType { get; set; }
public string HeaderType { get; set; }
public Boolean CheckboxField { get; set; }
public int DataFileMapPK { get; set; }
public Boolean IsHeaderRequired { get; set; }
public Boolean IsHeaderTypeMandatory { get; set; }
public int Sequence { get; set; }
}
}
Try this
XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCEDataFileMappingSaveProp));
ArrayOfCEDataFileMappingSaveProp result;
using (StringReader reader = new StringReader(xml))
result = (ArrayOfCEDataFileMappingSaveProp)serializer.Deserialize(reader);
List<ExportHeaderType> exportHeaderTypes = result.CEDataFileMappingSaveProp.Select(c => c.HeaderTypes.ExportHeaderType).ToList();
result (in json format)
[{"AppType":"LBX","DocType":"Batch","HeaderType":"Detail","CheckboxField":"true","DataFileMapPK":"4","IsHeaderRequired":"false","IsHeaderTypeMandatory":"true","Sequence":"0"},
{"AppType":"LBX","DocType":"Check","HeaderType":"Detail","CheckboxField":"true","DataFileMapPK":"4","IsHeaderRequired":"false","IsHeaderTypeMandatory":"true","Sequence":"0"}]
classes
[XmlRoot(ElementName = "ArrayOfCEDataFileMappingSaveProp", Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public class ArrayOfCEDataFileMappingSaveProp
{
[XmlElement(ElementName = "CEDataFileMappingSaveProp", Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public List<CEDataFileMappingSaveProp> CEDataFileMappingSaveProp { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName = "i", Namespace = "http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
}
[XmlRoot(ElementName="ExportHeaderType")]
public class ExportHeaderType {
[XmlElement(ElementName="AppType")]
public string AppType { get; set; }
[XmlElement(ElementName="DocType")]
public string DocType { get; set; }
[XmlElement(ElementName="HeaderType")]
public string HeaderType { get; set; }
[XmlElement(ElementName="CheckboxField")]
public bool CheckboxField { get; set; }
[XmlElement(ElementName="DataFileMapPK")]
public int DataFileMapPK { get; set; }
[XmlElement(ElementName="IsHeaderRequired")]
public bool IsHeaderRequired { get; set; }
[XmlElement(ElementName="IsHeaderTypeMandatory")]
public bool IsHeaderTypeMandatory { get; set; }
[XmlElement(ElementName="Sequence")]
public int Sequence { get; set; }
}
[XmlRoot(ElementName="HeaderTypes")]
public class HeaderTypes {
[XmlElement(ElementName="ExportHeaderType")]
public ExportHeaderType ExportHeaderType { get; set; }
}
[XmlRoot(ElementName="CEDataFileMappingSaveProp")]
public class CEDataFileMappingSaveProp {
[XmlElement(ElementName="HeaderTypes")]
public HeaderTypes HeaderTypes { get; set; }
[XmlElement(ElementName="DocAppTypeId")]
public string DocAppTypeId { get; set; }
[XmlElement(ElementName="DocTypeId")]
public string DocTypeId { get; set; }
[XmlElement(ElementName="IsHeadingAvailable")]
public bool IsHeadingAvailable { get; set; }
}
Related
I want to create the following JSON object string using C#. I am getting data from the database to set the data.
{
"markers":[
{
"articles":[
{
"ID":3759,
"post_type":"report",
"post_title":"No",
"post_url":"/report/",
"fields":[
{
"institution_name":"Georgetown"
},
{
"journal_name":"Jama"
},
{
"lead_author":{
"id":2214,
"name":"Kelly",
"slug":"dr",
"description":"director",
"image_object":{
"thumbnail":"test.png",
"thumbnail-width":150,
"thumbnail-height":150,
"medium":"test.png",
"medium-width":300,
"medium-height":300,
"medium_large":"test.png",
"medium_large-width":361,
"medium_large-height":361,
"large":"test.png",
"large-width":361,
"large-height":361
}
}
}
]
}
],
"location":{
"name":"location",
"include_on_map":true,
"address":null,
"lat":null,
"lng":null
}
},
{
"articles":[
{
"ID":1893,
"post_type":"report",
"post_title":"Controls",
"post_url":"/report/",
"fields":[
{
"institution_name":"System"
},
{
"journal_name":"World"
},
{
"lead_author":{
"id":1019,
"name":"Hardesty",
"slug":"hardesty",
"description":"",
"image_object":{
}
}
}
]
}
],
"location":{
"name":"location",
"include_on_map":true,
"address":"USA",
"lat":"38.12345",
"lng":"-70.12345"
}
}
],
"params":{
"path":"",
"raw_path":null,
"page":1,
"lang":"en",
"items":9,
"type":"",
"term":null,
"offset":0,
"direction":"DESC",
"order":"date",
"currentpagenumber":[
""
]
}
}
Could you please help me to create the json output using foreach loop?
Below is the code i am having currently.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON
{
class Program
{
static void Main(string[] args)
{
string jsonString = string.Empty;
Root root = new Root()
{
Markers = new List<Marker>
{
new Marker()
{
Articles = new List<Article>
{
new Article()
{
ID=1234,
PostTitle="Test",
}
},
Location = new Location()
{
Name="Location" ,
Address="USA",
}
}
},
Params = new Params()
{
Page = 1,
}
};
jsonString = JsonString(root);
Console.WriteLine(jsonString);
Console.ReadLine();
}
public static string JsonString(Root model)
{
string jsonString = JsonConvert.SerializeObject(model);
return jsonString;
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON
{
class JsonModel
{
}
public class ImageObject
{
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
[JsonProperty("thumbnail-width")]
public int ThumbnailWidth { get; set; }
[JsonProperty("thumbnail-height")]
public int ThumbnailHeight { get; set; }
[JsonProperty("medium")]
public string Medium { get; set; }
[JsonProperty("medium-width")]
public int MediumWidth { get; set; }
[JsonProperty("medium-height")]
public int MediumHeight { get; set; }
[JsonProperty("medium_large")]
public string MediumLarge { get; set; }
[JsonProperty("medium_large-width")]
public int MediumLargeWidth { get; set; }
[JsonProperty("medium_large-height")]
public int MediumLargeHeight { get; set; }
[JsonProperty("large")]
public string Large { get; set; }
[JsonProperty("large-width")]
public int LargeWidth { get; set; }
[JsonProperty("large-height")]
public int LargeHeight { get; set; }
}
public class LeadAuthor
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("slug")]
public string Slug { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("image_object")]
public ImageObject ImageObject { get; set; }
}
public class Field
{
[JsonProperty("institution_name")]
public string InstitutionName { get; set; }
[JsonProperty("journal_name")]
public string JournalName { get; set; }
[JsonProperty("lead_author")]
public LeadAuthor LeadAuthor { get; set; }
}
public class Article
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("post_type")]
public string PostType { get; set; }
[JsonProperty("post_title")]
public string PostTitle { get; set; }
[JsonProperty("post_url")]
public string PostUrl { get; set; }
[JsonProperty("fields")]
public List<Field> Fields { get; set; }
}
public class Location
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("include_on_map")]
public bool IncludeOnMap { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("lng")]
public string Lng { get; set; }
}
public class Marker
{
[JsonProperty("articles")]
public List<Article> Articles { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
}
public class Params
{
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("raw_path")]
public object RawPath { get; set; }
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("lang")]
public string Lang { get; set; }
[JsonProperty("items")]
public int Items { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("term")]
public object Term { get; set; }
[JsonProperty("offset")]
public int Offset { get; set; }
[JsonProperty("direction")]
public string Direction { get; set; }
[JsonProperty("order")]
public string Order { get; set; }
[JsonProperty("currentpagenumber")]
public List<string> Currentpagenumber { get; set; }
}
public class Root
{
[JsonProperty("markers")]
public List<Marker> Markers { get; set; }
[JsonProperty("params")]
public Params Params { get; set; }
}
}
I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
I am trying to (serialise?) a class in to JSON and am getting a null reference exception - please can you help me understand why and possible fix this?
I wrote a class which contains several nested classes (the JSON structure was provided by the UK carrier DPD).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DPDJSONLibrary
{
public class DPD_JSON
{
// insert shipment request
/// <summary>
/// Root Object. Insert Shipment Request
/// </summary>
public class IS
{
public string job_id { get; set; }
public bool collectionOnDelivery { get; set; }
public IS_Invoice invoice { get; set; }
public string collectionDate { get; set; }
public bool consolidate { get; set; }
public IS_Consignment consignment { get; set; }
}
public class IS_Address
{
public string addressId { get; set; }
public string countryCode { get; set; }
public string countryName { get; set; }
public string county { get; set; }
public string locality { get; set; }
public string organisation { get; set; }
public string postcode { get; set; }
public string street { get; set; }
public string town { get; set; }
}
public class IS_ContactDetails
{
public string contactName { get; set; }
public string telephone { get; set; }
}
public class IS_PickupLocation
{
public IS_Address address { get; set; }
public bool allowRemotePickup { get; set; }
public string pickupLocationCode { get; set; }
}
public class IS_NotificationDetails
{
public string email { get; set; }
public string mobile { get; set; }
}
public class IS_ParcelProduct
{
public string countryOfOrigin { get; set; }
public Int32 numberOfItems { get; set; }
public string productCode { get; set; }
public string productFabricContent { get; set; }
public string productHarmonisedCode { get; set; }
public string productItemsDescription { get; set; }
public string productTypeDescription { get; set; }
public decimal unitValue { get; set; }
public decimal unitWeight { get; set; }
}
public class IS_InvoiceItem
{
public string countryOfOrigin { get; set; }
public string itemCode { get; set; }
public string itemDescription { get; set; }
public int numberOfItems { get; set; }
public decimal unitValue { get; set; }
}
public class IS_InvoiceBillingDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public string vatNumber { get; set; }
}
public class IS_Invoice
{
public string countryOfOrigin { get; set; }
public IS_InvoiceBillingDetails invoiceBillingDetails { get; set; }
public string invoiceCustomsNumber { get; set; }
public string invoiceExportReason { get; set; }
public bool invoiceIsDeclared { get; set; }
public IS_InvoiceItem invoiceItem { get; set; }
public string invoiceTermsOfDelivery { get; set; }
public int invoiceType { get; set; }
public int totalItems { get; set; }
public decimal totalValue { get; set; }
public decimal totalWeight { get; set; }
}
public class IS_DeliveryDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public IS_NotificationDetails notificationDetails { get; set; }
public IS_PickupLocation deliveryDetails { get; set; }
}
public class IS_CollectionDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
}
public class IS_Parcels
{
public bool isVoided { get; set; }
public string labelNumber { get; set; }
public int packageNumber { get; set; }
public string parcelNumber { get; set; }
public IS_ParcelProduct parcelProduct { get; set; }
public string parcelnetBarcode { get; set; }
public string parcelnetData { get; set; }
public string parcelnetLabelNumber { get; set; }
}
public class IS_Consignment
{
public IS_CollectionDetails collectionDetails { get; set; }
public string consignmentNumber { get; set; }
public string consignmentRef { get; set; }
public decimal? customsValue { get; set; }
public IS_DeliveryDetails deliveryDetails { get; set; }
public string deliveryInstructions { get; set; }
public bool liability { get; set; }
public decimal liabilityValue { get; set; }
public string networkCode { get; set; }
public int numberOfParcels { get; set; }
public IS_Parcels parcel { get; set; }
public string parceldescription { get; set; }
public string shippingRef1 { get; set; }
public string shippingRef2 { get; set; }
public string shippingRef3 { get; set; }
public decimal totalWeight { get; set; }
}
}
}
I have another class containing public variables which I assign values to from code, and a method/function to instantiate my JSON class and pull in the values from the public variables.
I am getting a null reference exception on the line:
NewShipmentObject.consignment.consignmentNumber = null;
The error reads:
error System.NullReferenceException: Object reference not set to an instance of an object
The method I cam calling and getting the error in is below:
using System;
using System.Text;
using System.Net;
// include
using System.IO;
using System.Web.UI.WebControls;
using DPDJSONLibrary;
using System.Web;
using Newtonsoft.Json;
namespace DPDAPILibrary
{
public class DPD_API
{
#region public class variables
public string BusinessUnit;
public string DeliveryDirection;
public string NumberOfParcels;
public string ShipmentType;
public string TotalWeight;
public string CollectionDate;
public string ColName;
public string ColPhone;
public string ColOrganisation;
public string ColCountryCode;
public string ColPostCode;
public string ColStreet;
public string ColLocality;
public string ColTown;
public string ColCounty;
public string DelName;
public string DelPhone;
public string DelOrganisation;
public string DelCountryCode;
public string DelPostcode;
public string DelStreet;
public string DelLocality;
public string DelTown;
public string DelCounty;
public string DelNotificationEmail;
public string DelNotificationMobile;
public string NetworkCode;
public string ShippingRef1;
public string ShippingRef2;
public string ShippingRef3;
public string CustomsValue;
public string DeliveryInstructions;
public string ParcelDescription;
public string LiabilityValue;
public string Liability;
#endregion
public Boolean insertShipment(out string JSONData)
{
try
{
DPD_JSON.IS NewShipmentObject = new DPD_JSON.IS();
NewShipmentObject.job_id = null;
NewShipmentObject.collectionOnDelivery = false;
NewShipmentObject.invoice = null;
NewShipmentObject.collectionDate = CollectionDate;
NewShipmentObject.consolidate = false;
NewShipmentObject.consignment.consignmentNumber = null;
NewShipmentObject.consignment.consignmentRef = null;
NewShipmentObject.consignment.parcel = null;
NewShipmentObject.consignment.collectionDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.collectionDetails.contactDetails.telephone = ColPhone;
NewShipmentObject.consignment.collectionDetails.address.organisation = ColOrganisation;
NewShipmentObject.consignment.collectionDetails.address.countryCode = ColCountryCode;
NewShipmentObject.consignment.collectionDetails.address.postcode = ColPostCode;
NewShipmentObject.consignment.collectionDetails.address.street = ColStreet;
NewShipmentObject.consignment.collectionDetails.address.locality = ColLocality;
NewShipmentObject.consignment.collectionDetails.address.town = ColTown;
NewShipmentObject.consignment.collectionDetails.address.county = ColCounty;
NewShipmentObject.consignment.deliveryDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.deliveryDetails.contactDetails.telephone = DelPhone;
NewShipmentObject.consignment.deliveryDetails.address.organisation = DelOrganisation;
NewShipmentObject.consignment.deliveryDetails.address.countryCode = DelCountryCode;
NewShipmentObject.consignment.deliveryDetails.address.postcode = DelPostcode;
NewShipmentObject.consignment.deliveryDetails.address.street = DelStreet;
NewShipmentObject.consignment.deliveryDetails.address.locality = DelLocality;
NewShipmentObject.consignment.deliveryDetails.address.town = DelTown;
NewShipmentObject.consignment.deliveryDetails.address.county = DelCounty;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.email = DelNotificationEmail;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.mobile = DelNotificationMobile;
// default output value
JSONData = "";
JSONData = Convert.ToString(JsonConvert.SerializeObject(NewShipmentObject));
}
catch (Exception ex)
{
JSONData = Convert.ToString(ex);
return false;
}
}
}
}
You'll need to initialize all objects (including child entities) before you can use them*, as they will otherwise adopt their default values (which will be null for objects). i.e. replace
NewShipmentObject.consignment.consignmentNumber = null;
with:
NewShipmentObject.consignment = new IS_Consignment();
NewShipmentObject.consignment.consignmentNumber = null;
You can save yourself a lot of typing - instead of line-by-line setting of each field, you can do so using Object Initializer Syntax:
var NewShipmentObject = new DPD_JSON.IS
{
job_id = null,
collectionOnDelivery = false,
consignment = new IS_Consignment
{
consignmentNumber = null,
... more consignment settings here
}
... etc.
It should be noted that you don't need to explicitly set uninitialized variables to their default value, i.e. both
job_id = null,
collectionOnDelivery = false
are redundant, as these should be the default values in any event.
* (unless this initialization is done automatically in the constructor)
This is C# in VS2012 and building against .NET 4.5
I'm new to XML serialization/deserialization and trying to figure this out. I have XML
<?xml version="1.0"?>
<AvailabilityResponse>
<ApiKey>LZ6c#3O9#tq*BAyX4KGYBsCgZ*HpUDtrB*XI*WGLw</ApiKey>
<ResellerId>101</ResellerId>
<SupplierId>1004</SupplierId>
<ForeignReference>1234567890</ForeignReference>
<Timestamp>2015-08-06T05:20:49.000Z</Timestamp>
<RequestStatus>
<Status>SUCCESS</Status>
</RequestStatus>
<TTAsku>dcnt</TTAsku>
<TourAvailability>
<TourDate>2015-08-31</TourDate>
<TourOptions>
<DepartureTime>07:30 PM</DepartureTime>
</TourOptions>
<AvailabilityStatus>
<Status>AVAILABLE</Status>
</AvailabilityStatus>
</TourAvailability>
<TourAvailability>
<TourDate>2015-08-31</TourDate>
<TourOptions>
<DepartureTime>08:30 PM</DepartureTime>
</TourOptions>
<AvailabilityStatus>
<Status>AVAILABLE</Status>
</AvailabilityStatus>
</TourAvailability>
</AvailabilityResponse>
and I'm trying to deserialize into this class structure:
[Serializable]
public class AvailabilityResponse
{
public string ApiKey { get; set; }
public string ResellerId { get; set; }
public string SupplierId { get; set; }
public string ForeignReference { get; set; }
public DateTime Timestamp { get; set; }
public RequestStatus RequestStatus { get; set; }
public string TTAsku { get; set; }
public TourAvailability[] TourAvailability { get; set; }
}
[Serializable]
public class RequestStatus
{
public string Status { get; set; }
}
[Serializable]
public class TourAvailability
{
public DateTime TourDate { get; set; }
public TourOptions TourOptions { get; set; }
public AvailabilityStatus AvailabilityStatus { get; set; }
}
[Serializable]
public class AvailabilityStatus
{
public string Status { get; set; }
public string UnavailabilityReason { get; set; }
}
And I'm doing so with:
public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
{
XmlSerializer xmlSr = null;
XmlReader inreader = null;
if (replyStream != null)
{
XmlTextReader xmlreader = new XmlTextReader(replyStream);
XmlDocument respXml = new XmlDocument();
respXml.Load(xmlreader);
xmlreader.Close();
xmlSr = DeserializeXmlDoc(respXml, out inreader, typeof(AvailabilityResponse));
}
if (xmlSr != null && inreader != null)
{
AvailabilityResponse inventory = (AvailabilityResponse)xmlSr.Deserialize(inreader);
return inventory;
}
return null;
}
The problem is that when I examine the returned inventory item, the TourAvailability looks like this:
where I expected it to be like RequestStatus, for example, with the [+] allowing me to open it and see each element. Even if I misrepresented it I would expect there to be at least one TourAvailability, not zero.
I'm probably missing several things here but any help you can give is greatly appreciated. I have a bunch more of this kind of thing to deal with because our company is slightly changing direction.
Just use [XmlElement("TourAvailability")] attribute, Then you'll see the array's elemets.
public class AvailabilityResponse
{
public string ApiKey { get; set; }
public string ResellerId { get; set; }
public string SupplierId { get; set; }
public string ForeignReference { get; set; }
public DateTime Timestamp { get; set; }
public RequestStatus RequestStatus { get; set; }
public string TTAsku { get; set; }
[XmlElement("TourAvailability")]
public TourAvailability[] TourAvailability { get; set; }
}
BTW: You don't need those [Serializable] attributes
PS: Your deserialization code can be simplified as:
using (var f = File.OpenRead(filename))
{
XmlSerializer ser = new XmlSerializer(typeof(AvailabilityResponse));
var resp = (AvailabilityResponse)ser.Deserialize();
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Stream stream = File.Open(FILENAME, FileMode.Open);
AvailabilityResponse availabilityResponse = DeserializeAvailabilityResponse(stream);
}
public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
{
AvailabilityResponse availabilityResponse = null;
XmlReader inreader = null;
if (replyStream != null)
{
XmlSerializer xs = new XmlSerializer(typeof(AvailabilityResponse));
inreader = new XmlTextReader(replyStream);
availabilityResponse = (AvailabilityResponse)xs.Deserialize(inreader);
return availabilityResponse;
}
else
{
return null;
}
}
}
[XmlRoot("AvailabilityResponse")]
public class AvailabilityResponse
{
[XmlElement("ApiKey")]
public string ApiKey { get; set; }
[XmlElement("ResellerId")]
public int ResellerId { get; set; }
[XmlElement("SupplierId")]
public int SupplierId { get; set; }
[XmlElement("ForeignReference")]
public string ForeignReference { get; set; }
[XmlElement("Timestamp")]
public DateTime Timestamp { get; set; }
[XmlElement("RequestStatus")]
public RequestStatus RequestStatus { get; set; }
[XmlElement("TTAsku")]
public string TTAsku { get; set; }
[XmlElement("TourAvailability")]
public List<TourAvailability> TourAvailability { get; set; }
}
[XmlRoot("RequestStatus")]
public class RequestStatus
{
[XmlElement("Status")]
public string Status { get; set; }
}
[XmlRoot("TourAvailability")]
public class TourAvailability
{
[XmlElement("TourDate")]
public DateTime TourDate { get; set; }
[XmlElement("TourOptions")]
public TourOptions TourOptions { get; set; }
[XmlElement("AvailabilityStatus")]
public AvailabilityStatus AvailabilityStatus { get; set; }
}
[XmlRoot("TourOptions")]
public class TourOptions
{
public DateTime dTime { get; set; }
[XmlElement("DepartureTime")]
public string DepartureTime
{
get
{
return this.dTime.ToString("hh:mm tt");
}
set
{
this.dTime = DateTime.ParseExact(value, "hh:mm tt", CultureInfo.InvariantCulture);
}
}
}
[XmlRoot("AvailabilityStatus")]
public class AvailabilityStatus
{
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("UnavailabilityReason")]
public string UnavailabilityReason { get; set; }
}
}
I'm trying to deserialize an XML file which I receive from a vendor with XmlSerializer, however im getting this exception: There is an error in XML document (1, 2).InnerException Message "<delayedquotes xmlns=''> was not expected.. I've searched the stackoverflow forum, google and implemented the advice, however I'm still getting the same error. Please find the enclosed some content of the xml file:
<delayedquotes id="TestData">
<headings>
<title/>
<bid>bid</bid>
<offer>offer</offer>
<trade>trade</trade>
<close>close</close>
<b_time>b_time</b_time>
<o_time>o_time</o_time>
<time>time</time>
<hi.lo>hi.lo</hi.lo>
<perc>perc</perc>
<spot>spot</spot>
</headings>
<instrument id="Test1">
<title id="Test1">Test1</title>
<bid>0</bid>
<offer>0</offer>
<trade>0</trade>
<close>0</close>
<b_time>11:59:00</b_time>
<o_time>11:59:00</o_time>
<time>11:59:00</time>
<perc>0%</perc>
<spot>0</spot>
</instrument>
</delayedquotes>
and the code
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class delayedquotes
{
[XmlElement("instrument")]
public string instrument { get; set; }
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
public delayedquotes()
{
}
}
Maybe you can try this code:
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class DelayedQuotes
{
public DelayedQuotes()
{
instrument = new List<Instrument>();
}
[XmlElement("instrument")]
public List<Instrument> instrument { get; set; }
}
[XmlType("instrument")]
public class Instrument
{
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
}
Also, here is a sample code to test the classes above:
static void Main(string[] args)
{
Console.WriteLine("Initiating test!");
XmlSerializer serializer = new XmlSerializer(typeof(DelayedQuotes));
FileStream xmlFile = new FileStream("testXml.xml", FileMode.Open);
DelayedQuotes quotes = (DelayedQuotes) serializer.Deserialize(xmlFile);
Console.WriteLine("Finalizing test!");
}
Try this code.
var xml = System.IO.File.ReadAllText("test.xml");
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlSerializer serializer = new XmlSerializer(typeof(delayedquotes));
delayedquotes data = (delayedquotes) serializer.Deserialize(stream);
}
I am not sure how you're deserializing the XML text into your object, but the following worked fine for me:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XMLSerializationTest
{
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class delayedquotes
{
[XmlElement("instrument")]
public string instrument { get; set; }
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
public delayedquotes()
{
}
}
static class Program
{
static void Main(string[] args)
{
string source = #"<delayedquotes id=""TestData"">
<headings>
<title/>
<bid>bid</bid>
<offer>offer</offer>
<trade>trade</trade>
<close>close</close>
<b_time>b_time</b_time>
<o_time>o_time</o_time>
<time>time</time>
<hi.lo>hi.lo</hi.lo>
<perc>perc</perc>
<spot>spot</spot>
</headings>
<instrument id=""Test1"">
<title id=""Test1"">Test1</title>
<bid>0</bid>
<offer>0</offer>
<trade>0</trade>
<close>0</close>
<b_time>11:59:00</b_time>
<o_time>11:59:00</o_time>
<time>11:59:00</time>
<perc>0%</perc>
<spot>0</spot>
</instrument>
</delayedquotes>
";
var buff = Encoding.ASCII.GetBytes(source);
var ms = new MemoryStream(buff);
var xs = new XmlSerializer(typeof(delayedquotes));
var o = (delayedquotes)xs.Deserialize(ms);
Console.WriteLine("Title = {0}", o.instrument);
}
}
}