Deserialize XML with repeating elements - c#

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; }
}
}
​

Related

Read xml node value

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; }
}

Getting a JsonSerializationException when trying to deserialize PlayerStats

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"

C# - Create class to received list from HTTP Post response (XML)

I tried to received HTTP POST Reponse which is in XML Format, and has List inside using class
this is XML from server :
<list_bulk_response>
<status_code>1100</status_code>
<status_text>OK</status_text>
<list_request>
<request_bulk>
<request_status_code>1100</request_status_code>
<request_status_text>OK</request_status_text>
<id>1</id>
</request_bulk>
<request_bulk>
<request_status_code>1100</request_status_code>
<request_status_text>OK</request_status_text>
<id>2</id>
</request_bulk>
....
....
....
</list_request>
</list_bulk_response>
After search in many source, i try this :
public class list_bulk_response :
{
public string status_code { get; set; }
public string status_text { get; set; }
public list_request list_request { get; set; }
}
public class list_request
{
public List<request_bulk> request_bulk { get; set; }
}
public class request_bulk
{
public string request_status_code { get; set; }
public string request_status_text { get; set; }
public string id{ get; set; }
}
and this :
public class list_bulk_response : KenjaloApi
{
public List<list_request> list_request { get; set; }
}
public class list_request
{
public request_bulk request_bulk { get; set; }
}
public class request_bulk
{
public string request_status_code { get; set; }
public string request_status_text { get; set; }
public string request_date { get; set; }
public string transaction_id { get; set; }
public string priority { get; set; }
public string sender { get; set; }
public string dr_url { get; set; }
}
but still failed to received list that inside XML
UPDATE
this is my code to deserialize :
public static T deserializeXMLtoClass<T>(string input) where T : class
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(input))
{
return (T)ser.Deserialize(sr);
sr.Close();
}
}
Any wrong in my class?
Your first model is almost correct. You are just missing a simple hint [XmlElement("request_bulk")]
var t = deserializeXMLtoClass<list_bulk_response>(xmlstring);
public class list_bulk_response
{
public string status_code { get; set; }
public string status_text { get; set; }
public list_request list_request { get; set; }
}
public class list_request
{
[XmlElement("request_bulk")]
public List<request_bulk> request_bulk { get; set; }
}
public class request_bulk
{
public string request_status_code { get; set; }
public string request_status_text { get; set; }
public string id { get; set; }
}
You could do something like this
using (Stream httpResponseStream = response.Content.ReadAsStreamAsync().Result)
{
XDocument responseXML = XDocument.Load(httpResponseStream);
IEnumerable<XElement> listBulkResponseElements = responseXML.Root.
Elements("list_bulk_response");
foreach (XElement lbre in listBulkResponseElements)
{
list_bulk_response lbr = new list_bulk_response();
request_bulk rb = new request_bulk();
// Access the values with Element(valueName).value like this
lbr.statuscode = lbre.Element("statuscode").value;
lbr.statustext = lbre.Element("statustext").value;
// For nested elements you need to add extra Element(valueName)s like this
rb.request_status_code = Root.Element("list_request").Elements("request_bulk").
Element("request_status_code").value;
// Notice that "Element" is used where you only have one of them like with your
// "list_bulk_response" and "Elements" is used where you have multiple ones
// like with "request_bulk"
// And so on
// Now you need to decide what do do with your objects
}
}

Conversion of JSON object to C# object

Please consider the following code:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Net;
namespace wideeye4
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
}
/// <summary>
/// A collection for ItemViewModel objects.
/// </summary>
public ObservableCollection<ItemViewModel> Items { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its
value using a Binding
/// </summary>
/// <returns></returns>
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public void LoadData()
{
try
{
WebClient webclient = new WebClient();
Uri uri = new Uri(<http://192.168.100.100:3000/listings.json>);
webclient.OpenReadCompleted += new
OpenReadCompletedEventHandler(webclient_openreadcompleted);
webclient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webclient_openreadcompleted(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer serializer = null;
try
{
serializer = new
DataContractJsonSerializer(typeof(ObservableCollection<wideeye>));
e.Result.Position = 0;
var sr = new StreamReader(e.Result);
var json = sr.ReadToEnd();
ObservableCollection<wideeye> wideeyes = serializer.ReadObject(e.Result) as
ObservableCollection<wideeye>;
foreach (wideeye wd in wideeyes)
{
string varlisting_id = string.Empty;
string varlisting_image_file_name = string.Empty;
if (wd.listing != null)
{
string varcategory = wd.listing.category;
string varcity = wd.listing.city;
}
if (wd.listing_images != null)
{
varlisting_id = wd.listing_images.listing_id;
varlisting_image_file_name =
wd.listing_images.listing_image_file_name;
}
Items.Add(new ItemViewModel()
{ LineOne = wd.listing.category.ToString(),
LineTwo = wd.listing.city.ToString(),
LineThree =
string.Format("http://wideeye.hopto.org:3000/system/listing_images/{0}/medium/{1}",
varlisting_id, varlisting_image_file_name) });
}
this.IsDataLoaded = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
{
[DataContract]
public class wideeye
{
[DataMember]
public listing listing { get; set; }
[DataMember]
public listing_images listing_images { get; set; }
[DataMember]
public bids bids { get; set; }
[DataMember]
public messages messages { get; set; }
}
[DataContract]
public class listing
{
public string category { get; set; }
public string city { get; set; }
public string country { get; set; }
public string created_at { get; set; }
public string current_publish_date { get; set; }
public string details { get; set; }
public string id { get; set; }
public string industry { get; set; }
public string list_exp_date { get; set; }
public string list_price { get; set; }
public string list_start_date { get; set; }
public string make { get; set; }
public string model { get; set; }
public string open_bid { get; set; }
public string state { get; set; }
public string status { get; set; }
public string title { get; set; }
public string updated_at { get; set; }
public string year { get; set; }
}
[DataContract]
public class listing_images
{
public string created_at { get; set; }
public string id { get; set; }
public string listing_id { get; set; }
public string listing_image_content_type { get; set; }
public string listing_image_file_name { get; set; }
public string listing_image_file_size { get; set; }
public string listing_image_updated_at { get; set; }
public string updated_at { get; set; }
}
[DataContract]
public class bids
{
public string bid_exp_date { get; set; }
public string bid_price { get; set; }
public string bid_status { get; set; }
public string created_at { get; set; }
public string event_type { get; set; }
public string id { get; set; }
public string listing_id { get; set; }
public string msg_association_id { get; set; }
public string msg_text { get; set; }
public string msg_type { get; set; }
public string updated_at { get; set; }
public string user_id { get; set; }
}
[DataContract]
public class messages
{
public string bid_exp_date { get; set; }
public string bid_price { get; set; }
public string bid_status { get; set; }
public string created_at { get; set; }
public string event_type { get; set; }
public string id { get; set; }
public string listing_id { get; set; }
public string msg_association_id { get; set; }
public string msg_text { get; set; }
public string msg_type { get; set; }
public string updated_at { get; set; }
public string user_id { get; set; }
}
}
In webclient_openreadcompleted the event (e.result) is returning MemoryStream, so for that it is giving exception. I am facing a lot of problems as my JSON object is very large. I am using databoundWP7 model for this.
I can't be sure - your code sample is far too large...
But I think this code reads the whole of your result into a string and then tries to read the result a second time into the serializer:
var sr = new StreamReader(e.Result);
var json = sr.ReadToEnd();
ObservableCollection<wideeye> wideeyes = serializer.ReadObject(e.Result) as
ObservableCollection<wideeye>;
If that's true then it won't work - you can't read the stream twice (it's an incoming network stream!)

Deserialize an XML file - an error in xml document (1,2)

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);
}
}
}

Categories

Resources