Deserialize XML file in C# - c#

IDE: Microsoft Visual Studio 2010
Language : C#, XML
I am trying to deserialize XML file to object, but it throws me the error in XML document (5,4).Any suggestions ?
Here is the code I have tried ...
public void ReadXMLtblFieldingDetails(string xmlFileXDetails)
{
XmlSerializer serializer = new XmlSerializer(typeof(tblXDetails));
TextReader reader = new StreamReader(xmlXDetails);
object obj = serializer.Deserialize(reader);
tblXDetails XmlData = (tblXDetails)obj;
BusinessObjectManager.Add(XmlData);
}
And this is the XML document I want to deserialize ...
<?xml version="1.0"?>
<tblXDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<RowModified>0001-01-01T00:00:00</RowModified>
<MachineID>6A7FEBFDCEFC4DSSDAXX</MachineID>
<fielder1_x_axis>0</fielder1_x_axis>
<fielder1_y_axis>0</fielder1_y_axis>
<fielder2_x_axis>0</fielder2_x_axis>
<fielder2_y_axis>0</fielder2_y_axis>
<fielder3_x_axis>0</fielder3_x_axis>
<fielder3_y_axis>0</fielder3_y_axis>
<fielder4_x_axis>0</fielder4_x_axis>
<fielder4_y_axis>0</fielder4_y_axis>
<fielder5_x_axis>0</fielder5_x_axis>
<fielder5_y_axis>0</fielder5_y_axis>
<fielder6_x_axis>0</fielder6_x_axis>
<fielder6_y_axis>0</fielder6_y_axis>
<fielder7_x_axis>0</fielder7_x_axis>
<fielder7_y_axis>0</fielder7_y_axis>
<fielder8_x_axis>0</fielder8_x_axis>
<fielder8_y_axis>0</fielder8_y_axis>
<fielder9_x_axis>0</fielder9_x_axis>
<fielder9_y_axis>0</fielder9_y_axis>
</tblxDetails>
Here is the error : Error in XML Document(5,4) //Invalid Operation Exception was unhandled by user code
tblXDetails class:
public class tblXDetails
{
decimal _MachineID;
float _fielder1_x_axis;
float _fielder1_y_axis;
float _fielder2_x_axis;
float _fielder2_y_axis;
float _fielder3_x_axis;
float _fielder3_y_axis;
float _fielder4_x_axis;
float _fielder4_y_axis;
float _fielder5_x_axis;
float _fielder5_y_axis;
float _fielder6_x_axis;
float _fielder6_y_axis;
float _fielder7_x_axis;
float _fielder7_y_axis;
float _fielder8_x_axis;
float _fielder8_y_axis;
float _fielder9_x_axis;
float _fielder9_y_axis;
public decimal MachineID
{
get { return _MachineID; }
set { _MachineID = value; }
}
public float fielder1_x_axis
{
get { return _fielder1_x_axis; }
set { _fielder1_x_axis = value; }
}
public float fielder1_y_axis
{
get { return _fielder1_y_axis; }
set { _fielder1_y_axis = value; }
}
public float fielder2_x_axis
{
get { return _fielder2_x_axis; }
set { _fielder2_x_axis = value; }
}
public float fielder2_y_axis
{
get { return _fielder2_y_axis; }
set { _fielder2_y_axis = value; }
}
public float fielder3_x_axis
{
get { return _fielder3_x_axis; }
set { _fielder3_x_axis = value; }
}
public float fielder3_y_axis
{
get { return _fielder3_y_axis; }
set { _fielder3_y_axis = value; }
}
public float fielder4_x_axis
{
get { return _fielder4_x_axis; }
set { _fielder4_x_axis = value; }
}
public float fielder4_y_axis
{
get { return _fielder4_y_axis; }
set { _fielder4_y_axis = value; }
}
public float fielder5_x_axis
{
get { return _fielder5_x_axis; }
set { _fielder5_x_axis = value; }
}
public float fielder5_y_axis
{
get { return _fielder5_y_axis; }
set { _fielder5_y_axis = value; }
}
public float fielder6_x_axis
{
get { return _fielder6_x_axis; }
set { _fielder6_x_axis = value; }
}
public float fielder6_y_axis
{
get { return _fielder6_y_axis; }
set { _fielder6_y_axis = value; }
}
public float fielder7_x_axis
{
get { return _fielder7_x_axis; }
set { _fielder7_x_axis = value; }
}
public float fielder7_y_axis
{
get { return _fielder7_y_axis; }
set { _fielder7_y_axis = value; }
}
public float fielder8_x_axis
{
get { return _fielder8_x_axis; }
set { _fielder8_x_axis = value; }
}
public float fielder8_y_axis
{
get { return _fielder8_y_axis; }
set { _fielder8_y_axis = value; }
}
public float fielder9_x_axis
{
get { return _fielder9_x_axis; }
set { _fielder9_x_axis = value; }
}
public float fielder9_y_axis
{
get { return _fielder9_y_axis; }
set { _fielder9_y_axis = value; }
}

The MachineID must be a decimal (according to your class definition) but in the xml an incompatible value is provided: 6A7FEBFDCEFC4DSSDAXX. If you set it to 1 in the xml the serialization passes. I'm afraid you'll need to write a custom (de)serializer or change the type of the MachineID if possible.

Related

How can I create a method polymorphism?

I learn programming oriented object, and I want to do this code but I got those problems, I think I don't really know the concept of virtual.
View image 1
Code:
class Joueur
{
private string _nom;
private string _prenom;
private DateTime _dateDeNaissance;
private string _position;
private bool _reserve;
public string nom
{
get { return _nom; }
set { _nom = value; }
}
public string prenom
{
get { return _prenom; }
set { _prenom = value; }
}
public DateTime dateDeNaissance
{
get { return _dateDeNaissance; }
set { _dateDeNaissance = value; }
}
public string position
{
get { return _position; }
set { _position = value; }
}
public bool reserve
{
get { return _reserve; }
set { _reserve = value; }
}
public Joueur()
{
}
public Joueur(string nom, string prenom, DateTime dateDeNaissance, string position, bool reserve)
{
this.nom = nom;
this.prenom = prenom;
this.dateDeNaissance = dateDeNaissance;
this.position = position;
this.reserve = reserve;
}
public double virtual CalculerPrime(int joues, int gagnes)
{
double Prime;
if (reserve == false)
Prime = 10000 * (gagnes / joues);
else
Prime = ((10000 * (gagnes / joues)) / 2);
return Prime;
}
}
You need to do like this in your code:
public virtual double CalculerPrime(int joues, int gagnes)
{
double Prime;
if (reserve == false)
Prime = 10000 * (gagnes / joues);
else
Prime = ((10000 * (gagnes / joues)) / 2);
return Prime;
}

Why Query returns some null values to my list Object using dapper

I have this functional query where I only used fictive tables names for security concerns :
SELECT
h.CENID,
h.BMHFMC,
h.BMHDONEMIDASSTEP1,
h.BMHDONEMIDASSTEP2,
h.LMIID,
h.BMHHOLD,
h.BMHBATCHMIDAS,
h.BMHFMCVALUEDATE AS HeaderValueDate,
h.SUNID,
h.BRAID,
d.BMHID,
d.BMDRUBRIQUE,
d.BMDCLIENT,
d.BMDSEQUENCE,
d.BMDDATE,
d.BMDDEVISE,
d.BMDMONTANT,
d.BMDTYPE,
d.BMDNOTE,
d.BMDENTRYNBRE,
v.DEVDECIMAL ,
NVL(t.TYPVERIFCOMPTEMIDAS, 0) AS TYPVERIFCOMPTEMIDAS
FROM dbo.TableOne h
INNER JOIN dbo.Tabletwoo d
ON h.BMHID = d.BMHID
INNER JOIN dbo.tableThree v
ON d.BMDDEVISE = v.DEVID
LEFT JOIN dbo.TableFour t
ON t.TYPID=h.BMHFMC
WHERE d.BMDMONTANT != 0
AND h.BMHDONEMIDASSTEP1 = 0
AND h.BMHDONEMIDASSTEP2 = 0
AND h.LMIID = 0
AND h.BMHHOLD = 0
And I made a class in order to bind every fields
public class Batch :BaseRepository ,IList<Batch>
{
public Batch()
{
}
private string cendid;
private string bmhfmc;
private double bmhdonemidasstep1;
private double bmhdonemidasstep2;
private double lmiid;
private double bmhhold;
private double bmhbatchmidas;
private DateTime headervaluedateordinal;
private double sunid; //
private string bradid; //
private double bmhid;
private string bmdrubirique; //
private string bmdclient;
private string bmdsequence;
private DateTime bmddate;
private string bmddevise;
private double bmdmontant;
private string bmdtype;
private string bmdnote;
private string bmdentrynbre; //
private double devdecimalordinal;
private double typverifcomptemidasordinal;
public Batch(string cendid, string bmhfmc, double bmhdonemidasstep1, double bmhdonemidasstep2, double lmiid, double bmhhold, double bmhbatchmidas, DateTime headervaluedateordinal, double sunid, string bradid, double bmhid, string bmdrubirique, string bmdclient, string bmdsequence, DateTime bmddate, string bmddevise, double bmdmontant, string bmdtype, string bmdnote, string bmdentrynbre, double devdecimalordinal, double typverifcomptemidasordinal)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
this.bmhdonemidasstep1 = bmhdonemidasstep1;
this.bmhdonemidasstep2 = bmhdonemidasstep2;
this.lmiid = lmiid;
this.bmhhold = bmhhold;
this.bmhbatchmidas = bmhbatchmidas;
this.headervaluedateordinal = headervaluedateordinal;
this.sunid = sunid;
this.bradid = bradid;
this.bmhid = bmhid;
this.bmdrubirique = bmdrubirique;
this.bmdclient = bmdclient;
this.bmdsequence = bmdsequence;
this.bmddate = bmddate;
this.bmddevise = bmddevise;
this.bmdmontant = bmdmontant;
this.bmdtype = bmdtype;
this.bmdnote = bmdnote;
this.bmdentrynbre = bmdentrynbre;
this.devdecimalordinal = devdecimalordinal;
this.typverifcomptemidasordinal = typverifcomptemidasordinal;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
public double Bmhdonemidasstep1
{
get { return bmhdonemidasstep1; }
set { bmhdonemidasstep1 = value; }
}
public double Bmhdonemidasstep2
{
get { return bmhdonemidasstep2; }
set { bmhdonemidasstep2 = value; }
}
public double Lmiid
{
get { return lmiid; }
set { lmiid = value; }
}
public double Bmhhold
{
get { return bmhhold; }
set { bmhhold = value; }
}
public double Bmhbatchmidas
{
get { return bmhbatchmidas; }
set { bmhbatchmidas = value; }
}
public DateTime Headervaluedateordinal
{
get { return headervaluedateordinal; }
set { headervaluedateordinal = value; }
}
public double Sunid
{
get { return sunid; }
set { sunid = value; }
}
public string Bradid
{
get { return bradid; }
set { bradid = value; }
}
public double Bmhid
{
get { return bmhid; }
set { bmhid = value; }
}
public string Bmdrubirique
{
get { return bmdrubirique; }
set { bmdrubirique = value; }
}
public string Bmdclient
{
get { return bmdclient; }
set { bmdclient = value; }
}
public string Bmdsequence
{
get { return bmdsequence; }
set { bmdsequence = value; }
}
public DateTime Bmddate
{
get { return bmddate; }
set { bmddate = value; }
}
public string Bmddevise
{
get { return bmddevise; }
set { bmddevise = value; }
}
public double Bmdmontant
{
get { return bmdmontant; }
set { bmdmontant = value; }
}
public string Bmdtype
{
get { return bmdtype; }
set { bmdtype = value; }
}
public string Bmdnote
{
get { return bmdnote; }
set { bmdnote = value; }
}
public string Bmdentrynbre
{
get { return bmdentrynbre; }
set { bmdentrynbre = value; }
}
public double Devdecimalordinal
{
get { return devdecimalordinal; }
set { devdecimalordinal = value; }
}
public double Typverifcomptemidasordinal
{
get { return typverifcomptemidasordinal; }
set { typverifcomptemidasordinal = value; }
}
Now when I execute the query into a list using dapper
Connection conn = new Connection();
OracleConnection connection = conn.GetDBConnection();
myList= connection.Query<Batch>(querySql).ToList();
Now,while debugging, all fields returns the expected values .But, I noticed those fields below are null in myList not empty but really null , but the problem is they aren't null in the database
Bmdrubirique , Sunid, Bmdentrynbre, Bradid ,Cenid
In oracle database those fields are like the following :
CENID is VARCHAR2(3 BYTE)`
Bmhid is VARCHAR2(3 BYTE)
Sunid is NUMBER(38,0)
Bradid is VARCHAR2(3 BYTE)
I don't get it , where did it go wrong? why other fields are properly loaded while those returns null value ?
My default assumption would be that there is a typo in the real code and the constructor is assigning a value from a field to itself. However, frankly: since you have a public Batch() {} constructor, I'm not sure what the benefit of the second one is - it just adds risk of errors. Likewise with the fields and manual properties.
So if this as me, where you currently have (simplified to two properties):
public class Batch
{
private string cendid;
private string bmhfmc;
public Batch() {}
public Batch(string cendid, string bmhfmc)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
}
I would have literally just:
public class Batch
{
public string Cendid {get;set;}
public string Bmhfmc {get;set;}
}
All of the rest of the code is just opportunities to make coding errors.
Now: the reason that Cendid is null is because: the column is CENID - only one d. This means that dapper isn't even using your custom constructor, because it isn't a perfect match between the constructor and the columns. Ditto the other fields like BRAID vs BRADID.
So the next thing to do is to fix the typos.

CS0116 A name Space Cannot Directly Contain Members Such As Fields Or Methods

I don't know why the script I'm using won't work and I've tried a lot of times to get it to work, but it just doesn't. I've looked around on vids, sites and just everywhere but I can't find a solution. So now I hope I've come to the right place, but anyways here's the script and the error I'm getting.
using UnityEngine;
namespace UnitySampleAssets._2D
{
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Platf {
private PlatformerCharacter2D character;
private bool jump;
public object CrossPlatformInputManager { get; private set; }
public PlatformerCharacter2D Character
{
get
{
return Character2;
}
set
{
Character2 = value;
}
}
public bool Jump
{
get
{
return Jump2;
}
set
{
Jump2 = value;
}
}
public PlatformerCharacter2D Character1
{
get
{
return Character2;
}
set
{
Character2 = value;
}
}
public bool Jump1
{
get
{
return Jump2;
}
set
{
Jump2 = value;
}
}
public PlatformerCharacter2D Character2
{
get
{
return Character3;
}
set
{
Character3 = value;
}
}
public bool Jump2
{
get
{
return Jump3;
}
set
{
Jump3 = value;
}
}
public PlatformerCharacter2D Character3
{
get
{
return character;
}
set
{
character = value;
}
}
public bool Jump3
{
get
{
return jump;
}
set
{
jump = value;
}
}
private void Awake()
{
Character = GetComponent<PlatformerCharacter2D>();
}
private void Update()
{
if (!Jump)
// Read the jump input in Update so button presses aren't missed.
Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
private void FixedUpdate()
{
// Read the inputs.
bool crouch = Input.GetKey(KeyCode.LeftControl);
float h = CrossPlatformInputManager.GetAxis("Horizontal");
// Pass all parameters to the character control script.
Character.Move(h, crouch, Jump);
Jump = false;
}
}
}Platformer2DUserControl.cs : MonoBehaviour
And The Problem(s) im getting is 'CS0116 A name Space Cannot Directly Contain Members Such As Fields Or Methods' , and that 'Platformer2DUserControl.cs doesnt exist in the current context'
If you have a solution or a tip pls tell me.
Change your class definition to:
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Platf : MonoBehavior
{
// Implementation
} // remove: Platformer2DUserControl.cs : MonoBehaviour
The part after the closing bracket was interpreted as something you wanted to declare. To define inheritance, you just add : after the class name, followed by the name of the class you want to inherit from.
EDIT
In the end your code would look like this:
using UnityEngine;
namespace UnitySampleAssets._2D
{
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Platf : MonoBehavior {
private PlatformerCharacter2D character;
private bool jump;
public object CrossPlatformInputManager { get; private set; }
public PlatformerCharacter2D Character
{
get
{
return Character2;
}
set
{
Character2 = value;
}
}
public bool Jump
{
get
{
return Jump2;
}
set
{
Jump2 = value;
}
}
public PlatformerCharacter2D Character1
{
get
{
return Character2;
}
set
{
Character2 = value;
}
}
public bool Jump1
{
get
{
return Jump2;
}
set
{
Jump2 = value;
}
}
public PlatformerCharacter2D Character2
{
get
{
return Character3;
}
set
{
Character3 = value;
}
}
public bool Jump2
{
get
{
return Jump3;
}
set
{
Jump3 = value;
}
}
public PlatformerCharacter2D Character3
{
get
{
return character;
}
set
{
character = value;
}
}
public bool Jump3
{
get
{
return jump;
}
set
{
jump = value;
}
}
private void Awake()
{
Character = GetComponent<PlatformerCharacter2D>();
}
private void Update()
{
if (!Jump)
// Read the jump input in Update so button presses aren't missed.
Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
private void FixedUpdate()
{
// Read the inputs.
bool crouch = Input.GetKey(KeyCode.LeftControl);
float h = CrossPlatformInputManager.GetAxis("Horizontal");
// Pass all parameters to the character control script.
Character.Move(h, crouch, Jump);
Jump = false;
}
}
}

InnerException:When converting a string to DateTime. parse the string to date the date before putting each variable into the DateTime object

I am trying to deserialize XML returned from an API call but am getting "InnerException:When converting a string to DateTime. parse the string to date the date before putting each variable into the DateTime object"
The XML looks like this
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<agentInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:N1="demo.org.uk/demo/CustomsStatus" xmlns:N2="demo.org.uk/demo/UnLocation" xmlns:N3="demo.org.uk/demo/AirCarrier" xmlns="demo.org.uk/demo/AgentInventory">
<shed>ADX</shed>
<arrivalPort>
<N2:iataPortCode>LHR</N2:iataPortCode>
</arrivalPort>
<masterAirwayBillPrefix>125</masterAirwayBillPrefix>
<masterAirwayBillNumber>28121101</masterAirwayBillNumber>
<nominatedAgent>DRB</nominatedAgent>
<originPort>
<N2:iataPortCode>BOS</N2:iataPortCode>
</originPort>
<destinationPort>
<N2:iataPortCode>LHR</N2:iataPortCode>
</destinationPort>
<airCarrier>
<N3:carrierCode>BA</N3:carrierCode>
</airCarrier>
<flightNumber>235</flightNumber>
<flightDate>2012-02-09T00:00:00Z</flightDate>
<npx>10</npx>
<npr>0</npr>
<grossWeight>123.0</grossWeight>
<goodsDescription>BOOKS</goodsDescription>
<sdc>T</sdc>
<status1Set></status1Set>
<status2Set>false</status2Set>
<ccsCreationTime></ccsCreationTime>
<customsSummaryText />
<customsSummaryTime></customsSummaryTime>
<agentReference />
<isErtsPreArrival>false</isErtsPreArrival>
<isAgentPreArrival>false</isAgentPreArrival>
<isDeleted>false</isDeleted>
<finalised></finalised>
<createdOn>2012-01-24T11:50:40.86Z</createdOn>
<modifiedOn>2012-02-09T09:51:26.617Z</modifiedOn>
</agentInventory>
The code used to deserialize the XML is
if (storeXmlInventoryReturnData != null)
{
//DeSerialize XML from storeXmlInventoryReturnData variable
agentInventory myInventoryResponse = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(agentInventory));
myInventoryResponse = (
agentInventory)xmlSerializer.Deserialize(new StringReader(storeXmlInventoryReturnData)
);
Console.WriteLine(
#"\n\n\n INVENTORY RETURN DATA FOR AWB: {0}-{1} \n\n
Destination Port: {2} \n
Arrival Port: {3} \n
Carrier: {4} \n
Flight No: {5} \n
Flight Date: {6} \n
Customers Status: {7} \n
NPX: {8} \n
NPR {9} \n
SDC Code: {10}
\n\n Hit any key to exit...."
,
myInventoryResponse.masterAirwayBillPrefix,
myInventoryResponse.masterAirwayBillNumber,
myInventoryResponse.destinationPort,
myInventoryResponse.arrivalPort,
myInventoryResponse.airCarrier,
myInventoryResponse.flightNumber,
myInventoryResponse.flightDate,
myInventoryResponse.customsStatus,
myInventoryResponse.npx,
myInventoryResponse.npr,
myInventoryResponse.sdc,
myInventoryResponse.grossWeight,
myInventoryResponse.goodsDescription
);
Console.ReadLine();
}
else
{
Console.Write("No data returned");
}
}
The exception is thrown at;
myInventoryResponse = (
agentInventory)xmlSerializer.Deserialize(new StringReader(storeXmlInventoryReturnData));
I guess I need to convert the myInventoryResponse.flightDate to a DateTime object but I am at a loss how to achieve this?
namespace FreightSolutions {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="asm.org.uk/Sequoia/AgentInventory")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="demo.org.uk/demo/AgentInventory", IsNullable=false)]
public partial class agentInventory {
private string shedField;
private unLocation arrivalPortField;
private string masterAirwayBillPrefixField;
private string masterAirwayBillNumberField;
private string houseAirwayBillNumberField;
private string splitReferenceNumberField;
private string nominatedAgentField;
private unLocation originPortField;
private unLocation destinationPortField;
private airCarrier airCarrierField;
private string flightNumberField;
private System.DateTime flightDateField;
private bool flightDateFieldSpecified;
private string npxField;
private string nprField;
private float grossWeightField;
private bool grossWeightFieldSpecified;
private string goodsDescriptionField;
private string sdcField;
private System.DateTime status1SetField;
private bool status1SetFieldSpecified;
private bool status2SetField;
private bool status2SetFieldSpecified;
private System.DateTime ccsCreationTimeField;
private bool ccsCreationTimeFieldSpecified;
private customsStatus customsStatusField;
private string customsSummaryTextField;
private System.DateTime customsSummaryTimeField;
private bool customsSummaryTimeFieldSpecified;
private string agentReferenceField;
private bool isErtsPreArrivalField;
private bool isErtsPreArrivalFieldSpecified;
private bool isAgentPreArrivalField;
private bool isAgentPreArrivalFieldSpecified;
private bool isDeletedField;
private bool isDeletedFieldSpecified;
private System.DateTime finalisedField;
private bool finalisedFieldSpecified;
private System.DateTime createdOnField;
private System.DateTime modifiedOnField;
private bool modifiedOnFieldSpecified;
public agentInventory() {
this.customsStatusField = new customsStatus();
this.airCarrierField = new airCarrier();
this.destinationPortField = new unLocation();
this.originPortField = new unLocation();
this.arrivalPortField = new unLocation();
}
public string shed {
get {
return this.shedField;
}
set {
this.shedField = value;
}
}
public unLocation arrivalPort {
get {
return this.arrivalPortField;
}
set {
this.arrivalPortField = value;
}
}
public string masterAirwayBillPrefix {
get {
return this.masterAirwayBillPrefixField;
}
set {
this.masterAirwayBillPrefixField = value;
}
}
public string masterAirwayBillNumber {
get {
return this.masterAirwayBillNumberField;
}
set {
this.masterAirwayBillNumberField = value;
}
}
public string houseAirwayBillNumber {
get {
return this.houseAirwayBillNumberField;
}
set {
this.houseAirwayBillNumberField = value;
}
}
public string splitReferenceNumber {
get {
return this.splitReferenceNumberField;
}
set {
this.splitReferenceNumberField = value;
}
}
public string nominatedAgent {
get {
return this.nominatedAgentField;
}
set {
this.nominatedAgentField = value;
}
}
public unLocation originPort {
get {
return this.originPortField;
}
set {
this.originPortField = value;
}
}
public unLocation destinationPort {
get {
return this.destinationPortField;
}
set {
this.destinationPortField = value;
}
}
public airCarrier airCarrier {
get {
return this.airCarrierField;
}
set {
this.airCarrierField = value;
}
}
public string flightNumber {
get {
return this.flightNumberField;
}
set {
this.flightNumberField = value;
}
}
public System.DateTime flightDate {
get {
return this.flightDateField;
}
set {
this.flightDateField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool flightDateSpecified {
get {
return this.flightDateFieldSpecified;
}
set {
this.flightDateFieldSpecified = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]
public string npx {
get {
return this.npxField;
}
set {
this.npxField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]
public string npr {
get {
return this.nprField;
}
set {
this.nprField = value;
}
}
public float grossWeight {
get {
return this.grossWeightField;
}
set {
this.grossWeightField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool grossWeightSpecified {
get {
return this.grossWeightFieldSpecified;
}
set {
this.grossWeightFieldSpecified = value;
}
}
public string goodsDescription {
get {
return this.goodsDescriptionField;
}
set {
this.goodsDescriptionField = value;
}
}
public string sdc {
get {
return this.sdcField;
}
set {
this.sdcField = value;
}
}
public System.DateTime status1Set {
get {
return this.status1SetField;
}
set {
this.status1SetField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool status1SetSpecified {
get {
return this.status1SetFieldSpecified;
}
set {
this.status1SetFieldSpecified = value;
}
}
public bool status2Set {
get {
return this.status2SetField;
}
set {
this.status2SetField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool status2SetSpecified {
get {
return this.status2SetFieldSpecified;
}
set {
this.status2SetFieldSpecified = value;
}
}
public System.DateTime ccsCreationTime {
get {
return this.ccsCreationTimeField;
}
set {
this.ccsCreationTimeField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ccsCreationTimeSpecified {
get {
return this.ccsCreationTimeFieldSpecified;
}
set {
this.ccsCreationTimeFieldSpecified = value;
}
}
public customsStatus customsStatus {
get {
return this.customsStatusField;
}
set {
this.customsStatusField = value;
}
}
public string customsSummaryText {
get {
return this.customsSummaryTextField;
}
set {
this.customsSummaryTextField = value;
}
}
public System.DateTime customsSummaryTime {
get {
return this.customsSummaryTimeField;
}
set {
this.customsSummaryTimeField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool customsSummaryTimeSpecified {
get {
return this.customsSummaryTimeFieldSpecified;
}
set {
this.customsSummaryTimeFieldSpecified = value;
}
}
public string agentReference {
get {
return this.agentReferenceField;
}
set {
this.agentReferenceField = value;
}
}
public bool isErtsPreArrival {
get {
return this.isErtsPreArrivalField;
}
set {
this.isErtsPreArrivalField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isErtsPreArrivalSpecified {
get {
return this.isErtsPreArrivalFieldSpecified;
}
set {
this.isErtsPreArrivalFieldSpecified = value;
}
}
public bool isAgentPreArrival {
get {
return this.isAgentPreArrivalField;
}
set {
this.isAgentPreArrivalField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isAgentPreArrivalSpecified {
get {
return this.isAgentPreArrivalFieldSpecified;
}
set {
this.isAgentPreArrivalFieldSpecified = value;
}
}
public bool isDeleted {
get {
return this.isDeletedField;
}
set {
this.isDeletedField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isDeletedSpecified {
get {
return this.isDeletedFieldSpecified;
}
set {
this.isDeletedFieldSpecified = value;
}
}
public System.DateTime finalised {
get {
return this.finalisedField;
}
set {
this.finalisedField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool finalisedSpecified {
get {
return this.finalisedFieldSpecified;
}
set {
this.finalisedFieldSpecified = value;
}
}
public System.DateTime createdOn {
get {
return this.createdOnField;
}
set {
this.createdOnField = value;
}
}
public System.DateTime modifiedOn {
get {
return this.modifiedOnField;
}
set {
this.modifiedOnField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool modifiedOnSpecified {
get {
return this.modifiedOnFieldSpecified;
}
set {
this.modifiedOnFieldSpecified = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/UnLocation")]
public partial class unLocation {
private string itemField;
private ItemChoiceType itemElementNameField;
[System.Xml.Serialization.XmlElementAttribute("iataPortCode", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("oceanPortCode", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public string Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType ItemElementName {
get {
return this.itemElementNameField;
}
set {
this.itemElementNameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/UnLocation", IncludeInSchema=false)]
public enum ItemChoiceType {
/// <remarks/>
iataPortCode,
/// <remarks/>
oceanPortCode,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/CustomsStatus")]
public partial class customsStatus {
private string codeField;
private string statusTextField;
public string code {
get {
return this.codeField;
}
set {
this.codeField = value;
}
}
public string statusText {
get {
return this.statusTextField;
}
set {
this.statusTextField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/AirCarrier")]
public partial class airCarrier {
private string carrierCodeField;
public string carrierCode {
get {
return this.carrierCodeField;
}
set {
this.carrierCodeField = value;
}
}
}
}
For my own sanity sake, I tried getting the provided XML to work with your classes and the nullable DateTime fields.
For them to work, replace the below properties with those linked below.
The default value for a DateTime object is DateTime.MinDate, so if the incoming value is null or empty, then the property will have a value of DateTime.MinDate anyway, for this you might need to additional validation/changes if your code needs to cater for this.
#region XML Nullable helper properties
[XmlElement(ElementName = "status1Set")]
public object status1SetXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return status1Set;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out status1SetField);
}
}
}
[XmlElement(ElementName="ccsCreationTime")]
public object ccsCreationTimeXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return ccsCreationTime;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out ccsCreationTimeField);
}
}
}
[XmlElement(ElementName = "customsSummaryTime")]
public object customsSummaryTimeXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return customsSummaryTime;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out customsSummaryTimeField);
}
}
}
[XmlElement(ElementName = "finalised")]
public object finalisedXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return finalised;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out finalisedField);
}
}
}
#endregion
#region Non XML properties
[XmlIgnore]
public System.DateTime status1Set
{
get { return this.status1SetField; }
set { this.status1SetField = value; }
}
[XmlIgnore]
public System.DateTime ccsCreationTime
{
get { return this.ccsCreationTimeField; }
set { this.ccsCreationTimeField = value; }
}
[XmlIgnore]
public System.DateTime customsSummaryTime
{
get { return this.customsSummaryTimeField; }
set { this.customsSummaryTimeField = value; }
}
[XmlIgnore]
public System.DateTime finalised
{
get { return this.finalisedField; }
set { this.finalisedField = value; }
}
#endregion

JsonConvert.SerializeObject() fails in serializing class with DateTime fields

I'm having a class with only private fields and their public getter-setters. I need to convert class object into JSON String hence I'm using JSON.Net.
Following is a simple snippet to convert class object into a JSON string.
MyClass obj = new MyClass();
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
But the method SerializeObject throws StackOverflowException at field in MyClass of type DateTime. What's happening here?
Update
Following is how MyClass looks like (as it is, I don't mind sharing the actual class)
class MyClass
{
private int _Model;
public int Model
{
get
{
return _Model;
}
set
{
_Model = value;
}
}
private long _ProductionControlNumber;
public long ProductionControlNumber
{
get
{
return _ProductionControlNumber;
}
set
{
_ProductionControlNumber = value;
}
}
private DateTime _ProductionDate;
public DateTime ProductionDate
{
get
{
return _ProductionDate;
}
set
{
_ProductionDate = value;
}
}
private DateTime _TestDate;
public DateTime TestDate
{
get
{
return _TestDate;
}
set
{
_TestDate = value;
}
}
private DateTime _TestStartTime;
public DateTime TestStartTime
{
get
{
return _TestStartTime;
}
set
{
_TestStartTime = value;
}
}
private TimeSpan _TestDuration;
public TimeSpan TestDuration
{
get
{
return _TestDuration;
}
set
{
_TestDuration = value;
}
}
public DateTime TestEndTime
{
get
{
//TODO Perform start end time computing logic.
return TestEndTime;
}
}
private int _TestBed;
public int TestBed
{
get
{
return _TestBed;
}
set
{
_TestBed = value;
}
}
private long _EngineSerial;
public long EngineSerial
{
get
{
return _EngineSerial;
}
set
{
_EngineSerial = value;
}
}
private Single _FuelSpecificGravity;
public Single FuelSpecificGravity
{
get
{
return _FuelSpecificGravity;
}
set
{
_FuelSpecificGravity = value;
}
}
private long _FuelConsume100;
public long FuelConsume100
{
get
{
return _FuelConsume100;
}
set
{
_FuelConsume100 = value;
}
}
private long _FuelConsume110;
public long FuelConsume110
{
get
{
return _FuelConsume100;
}
set
{
_FuelConsume100 = value;
}
}
private int _TemporaryRPM;
public int TemporaryRPM
{
get
{
return _TemporaryRPM;
}
set
{
_TemporaryRPM = value;
}
}
private int _PermanentRPM;
public int PermanentRPM
{
get
{
return _PermanentRPM;
}
set
{
_PermanentRPM = value;
}
}
private Single _RatedPower;
public Single RatedPower
{
get
{
return _RatedPower;
}
set
{
_RatedPower = value;
}
}
private int _RatedSpeed;
public int RatedSpeed
{
get
{
return _RatedSpeed;
}
set
{
_RatedSpeed = value;
}
}
private double _PulleyDiameter;
public double PulleyDiameter
{
get
{
return _PulleyDiameter;
}
set
{
_PulleyDiameter = value;
}
}
private double _RopeDiameter;
public double RopeDiameter
{
get
{
return _RopeDiameter;
}
set
{
_RopeDiameter = value;
}
}
private Single _FullLoad;
public Single FullLoad
{
get
{
return _FullLoad;
}
set
{
_FullLoad = value;
}
}
}
Also, I'll have another class which will have MyClass type field (along with its own similar set of fields), which is going to be converted into JSON string too, and that shouldn't be a problem since JSON.Net is said to support that situation too.
Note: I'm new to C# but I've previously worked with JSON in Java, where I get to play with JSONObject and JSONArray, and they were pretty straight forward.
It looks like your TestEndTime property's getter references itself. Therefore when Json.NET tries to serialize it, it recursively accesses itself and causes the StackOverflowException.
Hope that helps!

Categories

Resources