I have a few questions about deserializing an xml file into an object that has been bothering me for almost two days. I appreciate any help anyone can offer!
I used xsd.exe to generate c# classes from the schema files. I then used XMLExplorer to create a sample XML file. Is it a correct assumption that if I save that sample file, unchanged, with the sample text values, and deserialize it into the appropriate c# class, that it "should" read the values and put them into the appropriate objects???
Does the XMLDeserializer REQUIRE that all elements be present in the XML file or can an XML file contain missing elements and still be deserialized correctly (by, for instance, putting null values in missing properties)???
I've read that XMLSerializer only checks for three errors and I've got those resolved by tagging the xmlroot and removing a broken URL. My code runs, but I'm getting nulls for "InvokingBusinessActivity" and "Passenger" and other properties.
Here's my deserialization code.
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader("C:\\Airports\\Projects_Current\\Multi-channel\\Dev\\Integration\\MCUniversalBagDropAPITester\\IataXmlSchemas\\Test Xml Files\\PassengerIdentifyRequest.xml");
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
here's my class that was generate from XSD. This is trimmed down because it is about 1000 lines:
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.iata.org/IATA/2007/00")]
[System.Xml.Serialization.XmlRootAttribute("IATA_PassengerConformanceIdentifyRQ", IsNullable = false)] /* I commented out and obfuscated defective Namespace="http://ww w.iat a.org/IATA/2007/00",*/
public partial class IATA_PassengerConformanceIdentifyRQ
{
private SourceType[] originatorField;
private BusinessActivityType invokingBusinessActivityField;
private IATA_PassengerConformanceIdentifyRQPassenger passengerField;
private string echoTokenField;
private System.DateTime timeStampField;
private bool timeStampFieldSpecified;
private IATA_PassengerConformanceIdentifyRQTarget targetField;
private decimal versionField;
private string transactionIdentifierField;
private string sequenceNmbrField;
private IATA_PassengerConformanceIdentifyRQTransactionStatusCode transactionStatusCodeField;
private bool transactionStatusCodeFieldSpecified;
private bool retransmissionIndicatorField;
private bool retransmissionIndicatorFieldSpecified;
private string correlationIDField;
private bool asynchronousAllowedIndField;
private bool asynchronousAllowedIndFieldSpecified;
public IATA_PassengerConformanceIdentifyRQ() {
this.targetField = IATA_PassengerConformanceIdentifyRQTarget.Production;
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Source", IsNullable=false)]
public SourceType[] Originator {
get {
return this.originatorField;
}
set {
this.originatorField = value;
}
}
/// <remarks/>
public BusinessActivityType InvokingBusinessActivity {
get {
return this.invokingBusinessActivityField;
}
set {
this.invokingBusinessActivityField = value;
}
}
ETC......
Here's the test file that was created by VS2010 XMLSchema Explorer. For simplicity, duplicate elements of "complex type" were removed. The broken URL was also removed and I added the xml version to the top to fix serialization issues.
<?xml version="1.0" encoding="utf-8"?>
<IATA_PassengerConformanceIdentifyRQ>
<!-- EchoToken="EchoToken1" TimeStamp="1900-01-01T01:01:01-06:00" Target="Production" Version="1" TransactionIdentifier="TransactionIdentifier1" SequenceNmbr="32" TransactionStatusCode="Start" PrimaryLangID="en" AltLangID="en" RetransmissionIndicator="true" CorrelationID="CorrelationID1" AsynchronousAllowedInd="true" xmlns="ht tp: // www . iata.org/IATA/2007/00" -->
<Originator>
<Source AgentSine="AgentSine1" PseudoCityCode="PseudoCityCode1" ISOCountry="ISOCountry1" ISOCurrency="ISOCurrency1" AgentDutyCode="AgentDutyCode1" AirlineVendorID="AirlineVendorID1" AirportCode="AirportCode1" FirstDepartPoint="Fi1" ERSP_UserID="ERSP_UserID1" TerminalID="TerminalID1">
<RequestorID MessagePassword="MessagePassword1" URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</RequestorID>
<Position Latitude="Latitude1" Longitude="Longitude1" Altitude="Altitude1" AltitudeUnitOfMeasureCode="AltitudeUnitOfMeasureCode1" />
<BookingChannel Type="Type1" Primary="true">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</BookingChannel>
</Source>
</Originator>
<InvokingBusinessActivity Code="06">Baggage Processing</InvokingBusinessActivity>
<Passenger>
<GUID>GUID1</GUID>
<NativeID>NativeID1</NativeID>
<Name ShareSynchInd="Yes" ShareMarketInd="Yes" NameType="NameType1">
<NamePrefix>NamePrefix1</NamePrefix>
<NamePrefix>NamePrefix2</NamePrefix>
<NamePrefix>NamePrefix3</NamePrefix>
<GivenName>GivenName1</GivenName>
<GivenName>GivenName2</GivenName>
<GivenName>GivenName3</GivenName>
<MiddleName>MiddleName1</MiddleName>
<MiddleName>MiddleName2</MiddleName>
<MiddleName>MiddleName3</MiddleName>
<SurnamePrefix>SurnamePrefix1</SurnamePrefix>
<Surname>Surname1</Surname>
<NameSuffix>NameSuffix1</NameSuffix>
<NameSuffix>NameSuffix2</NameSuffix>
<NameSuffix>NameSuffix3</NameSuffix>
<NameTitle>NameTitle1</NameTitle>
<NameTitle>NameTitle2</NameTitle>
<NameTitle>NameTitle3</NameTitle>
</Name>
<CustomerLoyalty ShareSynchInd="Yes" ShareMarketInd="Yes" ProgramID="ProgramID1" MembershipID="MembershipID1" TravelSector="TravelSector1" LoyalLevel="LoyalLevel1" SingleVendorInd="SingleVndr" SignupDate="1900-01-01" EffectiveDate="1900-01-01" ExpireDate="1900-01-01" RPH="RPH1" VendorCode="VendorC1 VendorC2 VendorC3 " />
<CustomerLoyalty ShareSynchInd="No" ShareMarketInd="No" ProgramID="ProgramID2" MembershipID="MembershipID2" TravelSector="TravelSector2" LoyalLevel="LoyalLevel2" SingleVendorInd="Alliance" SignupDate="0001-01-01" EffectiveDate="0001-01-01" ExpireDate="0001-01-01" RPH="RPH2" VendorCode="VendorC4 VendorC5 VendorC6 " />
<BoardingPass>
<ForIndividualAirlineUse>ForIndividualAirlineUse1</ForIndividualAirlineUse>
<DigitalSignature Type="1">DigitalSignature1</DigitalSignature>
</BoardingPass>
<Segment>
<PNR URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1" />
<NativeID>NativeID1</NativeID>
<Flight>
<NativeID>NativeID1</NativeID>
<OperatingCarrier>Op1</OperatingCarrier>
<FlightNumber>FlightNumber1</FlightNumber>
<OperationalSuffix>OperationalSuffix1</OperationalSuffix>
<MarketingCarrier>Ma1</MarketingCarrier>
<ScheduledDateOfDeparture>1900-01-01</ScheduledDateOfDeparture>
<ScheduledTimeOfDeparture>01:01:01</ScheduledTimeOfDeparture>
<ScheduledDateOfArrival>1900-01-01</ScheduledDateOfArrival>
<ScheduledTimeOfArrival>01:01:01</ScheduledTimeOfArrival>
</Flight>
<DepartureAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</DepartureAirport>
<ArrivalAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</ArrivalAirport>
<Cabin>Cabin1</Cabin>
<SeatNumber>SeatNumber1</SeatNumber>
<CheckInSequenceNumber>Chec1</CheckInSequenceNumber>
</Segment>
</Passenger>
</IATA_PassengerConformanceIdentifyRQ>
I'm doing something wrong and I'm not certain exactly what!!! Can someone please advise???
Try code below. I did some spot checking for errors, but there still may be some issue. I read XML from a different filename so you need to go back to your original filename.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader(FILENAME);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
XmlSerializer serializer = new XmlSerializer(typeof(IATA_PassengerConformanceIdentifyRQ));
StreamWriter writer = new StreamWriter(#"c:\temp\test1.xml");
serializer.Serialize(writer, localIataReq);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
[XmlRoot("IATA_PassengerConformanceIdentifyRQ")]
public partial class IATA_PassengerConformanceIdentifyRQ
{
[XmlElement("Originator")]
public Originator originator { get; set;}
[XmlElement("InvokingBusinessActivity")]
public InvokingBusinessActivity invokingBusinessActivity { get; set; }
[XmlElement("Passenger")]
public Passenger passenger { get; set; }
}
[XmlRoot("Originator")]
public partial class Originator
{
[XmlElement("Source")]
public Source source { get; set;}
}
[XmlRoot("Source")]
public class Source
{
[XmlAttribute("AgentSine")]
public string agentSine { get; set; }
[XmlAttribute("PseudoCityCode")]
public string pseudoCityCode { get; set; }
[XmlAttribute("ISOCountry")]
public string iSOCountry { get; set; }
[XmlAttribute("ISOCurrency")]
public string iSOCurrency { get; set; }
[XmlAttribute("AgentDutyCode")]
public string agentDutyCode { get; set; }
[XmlAttribute("AirlineVendorID")]
public string airlineVendorID { get; set; }
[XmlAttribute("AirportCode")]
public string airportCode { get; set; }
[XmlAttribute("FirstDepartPoint")]
public string firstDepartPoint { get; set; }
[XmlAttribute("ERSP_UserID")]
public string eRSP_UserID { get; set; }
[XmlAttribute("TerminalID")]
public string terminalID { get; set; }
[XmlElement("RequestorID")]
public RequestorID requestorID { get; set; }
[XmlElement("Position")]
public Position position { get; set; }
[XmlElement("BookingChannel")]
public BookingChannel bookingChannel { get; set; }
}
[XmlRoot("RequestorID")]
public class RequestorID
{
[XmlAttribute("MessagePassword")]
public string messagePassword { get; set; }
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Position")]
public partial class Position
{
[XmlAttribute("Latitude")]
public string latitude { get; set; }
[XmlAttribute("Longitude")]
public string longitude { get; set; }
[XmlAttribute("Altitude")]
public string altitude { get; set; }
[XmlAttribute("AltitudeUnitOfMeasureCode")]
public string altitudeUnitOfMeasureCode { get; set; }
}
[XmlRoot("BookingChannel")]
public class BookingChannel
{
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Primary")]
public Boolean primary { get; set; }
[XmlElement("CompanyName")]
public CompanyName companyName { get; set; }
}
[XmlRoot("CompanyName")]
public class CompanyName
{
[XmlAttribute("CompanyShortName")]
public string companyShortName { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("Code")]
public string code { get; set; }
[XmlAttribute("CodeContext")]
public string codeContext { get; set; }
[XmlText]
public string name { get; set; }
}
[XmlRoot("InvokingBusinessActivity")]
public class InvokingBusinessActivity
{
[XmlAttribute("Code")]
public string code { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Passenger")]
public class Passenger
{
[XmlElement("GUID")]
public Value guid { get; set; }
[XmlElement("NativeID")]
public Value nativeID { get; set; }
[XmlElement("Name")]
public Name name { get; set; }
[XmlElement("CustomerLoyalty")]
public List<CustomerLoyalty> customerLoyalty { get; set; }
[XmlElement("BoardingPass")]
public BoardingPass boardingPass { get; set; }
[XmlElement("Segment")]
public Segment segment { get; set; }
}
public class Value
{
[XmlText]
public string value { get; set; }
}
[XmlRoot("Name")]
public class Name
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("NameType")]
public string NameType { get; set; }
[XmlElement("NamePrefix")]
public List<string> namePrefix { get; set; }
[XmlElement("GivenName")]
public List<string> givenName { get; set; }
[XmlElement("MiddleName")]
public List<string> middleName { get; set; }
[XmlElement("SurnamePrefix")]
public List<string> surnamePrefix { get; set; }
[XmlElement("Surname")]
public List<string> surname { get; set; }
[XmlElement("NameSuffix")]
public string nameSuffix { get; set; }
[XmlElement("NameTitle")]
public string nameTitle { get; set; }
}
[XmlRoot("CustomerLoyalty")]
public class CustomerLoyalty
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("ProgramID")]
public string programID { get; set; }
[XmlAttribute("MembershipID")]
public string membershipID { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("LoyalLevel")]
public string loyalLevel { get; set; }
[XmlAttribute("SingleVendorInd")]
public string singleVendorInd { get; set; }
[XmlAttribute("SignupDate")]
public DateTime signupDate { get; set; }
[XmlAttribute("EffectiveDate")]
public DateTime effectiveDate { get; set; }
[XmlAttribute("ExpireDate")]
public DateTime expireDate { get; set; }
[XmlAttribute("RPH")]
public string rph { get; set; }
[XmlAttribute("VendorCode")]
public string vendorCode { get; set; }
}
[XmlRoot("BoardingPass")]
public class BoardingPass
{
[XmlElement("ForIndividualAirlineUse")]
public string forIndividualAirlineUse { get; set; }
[XmlElement("DigitalSignature")]
public DigitalSignature digitalSignature { get; set; }
}
[XmlRoot("DigitalSignature")]
public class DigitalSignature
{
[XmlAttribute("Type")]
public int _type { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Segment")]
public class Segment
{
[XmlElement("PNR")]
public PNR pnr { get; set; }
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("Flight")]
public Flight flight { get; set; }
[XmlElement("DepartureAirport")]
public Airport departureAirport { get; set; }
[XmlElement("ArrivalAirport")]
public Airport arrivalAirport { get; set; }
[XmlElement("Cabin")]
public string cabin { get; set; }
[XmlElement("SeatNumber")]
public string seatNumber { get; set; }
[XmlElement("CheckInSequenceNumber")]
public string checkInSequenceNumber { get; set; }
}
[XmlRoot("PNR")]
public class PNR
{
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string Instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Flight")]
public class Flight
{
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("OperatingCarrier")]
public string operatingCarrier { get; set; }
[XmlElement("FlightNumber")]
public string flightNumber { get; set; }
[XmlElement("OperationalSuffix")]
public string operationalSuffix { get; set; }
[XmlElement("MarketingCarrier")]
public string marketingCarrier { get; set; }
[XmlElement("ScheduledDateOfDeparture")]
public DateTime scheduledDateOfDeparture { get; set; }
[XmlElement("ScheduledTimeOfDeparture")]
public DateTime scheduledTimeOfDeparture { get; set; }
[XmlElement("ScheduledDateOfArrival")]
public DateTime scheduledDateOfArrival { get; set; }
[XmlElement("ScheduledTimeOfArrival")]
public DateTime scheduledTimeOfArrival { get; set; }
}
public class Airport
{
[XmlElement("AirportCode")]
public string airportCode { get; set; }
[XmlElement("SourceIndicator")]
public int sourceIndicator { get; set; }
}
}
Okay. Weird. I created a whole new project on a different development machine and ran through the entire process with all clean XSD->CS and XSD->Sample XML and this code works fine. SO I guess I delete this question or someone can post an answer along the lines of "start over." The only step I know for certain that was different happened when I dragged the header tag from the XMLSchemaExplorer to the designer worksurface instead of the IATA_PASSENGERCONFORMANCEIDENTIFYRQ element. That generated a giant tree of branches, rather than the single node. This could have caused the issue BUT something else that might have happened: I suspect VS2010 on the older project kept references to earlier incarnations of the classes, or referenced wrong versions in backup folders. (This actually does happen with older VS versions.)
Related
Hello I have one json text inside this text there is one key which starts with $
string jsonText="{\"Version\":\"1.1\",\"Documents\":[{\"DocumentState\":\"Correct\",\"DocumentData\":{\"Name\":\"test\",\"$type\":\"Document\",\"Fields\":[{\"Name\":\"CustomerFullName\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerBirthDate\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentNumber\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0000000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerIsMarried\",\"$type\":\"Checkmark\",\"IsSuspicious\":false,\"Value\":true},{\"Name\":\"CustomerCounty\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerArea\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerAddress\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"11000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"DocumentGUID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentProposalID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentCountry\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"FRA\",\"Value\":\"FRA\"},{\"Name\":\"DocumentCurrency\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"EUR\",\"Value\":\"EUR\"},{\"Name\":\"DocumentTo\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentFrom\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentTotalNumberOfPages\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"1\",\"Value\":\"1\"}]}}]}";
Console.WriteLine(jsonText);
var documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
and my class objects are below
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
but it is not working not converting $type to type. How can I solve this problem ?
Thanks in advance
Kind Regards
That's because you're using JsonConvert from Newtonsoft.Json library and are marking property with JsonPropertyName attribute from System.Text.Json.Serialization. The two just don't play well together. Try replacing your JsonPropertyName with JsonProperty attribute from Newtonsoft.Json and it should work.
public class DocumentData
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
Hi I'm working on Developing a Web-API project, which connects and working with multi-devices. I have one requirement like print XML format directly in mobile print device(WizarPOS), i need to send response format as given below.
<RESPONSE TYPE="PRINT" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TERMINALID>993324</TERMINALID>
<LOCALDATETIME>2018-11-16 09:08:40</LOCALDATETIME>
<SERVERDATETIME>6/29/2018 3:33:34 PM</SERVERDATETIME>
<TXID>880034435</TXID>
<HOSTTXID>ID00008769249</HOSTTXID>
<AMOUNT>500</AMOUNT>
<CURRENCY>634</CURRENCY>
<LIMIT>0</LIMIT>
<RECEIPT>
<LINES>14</LINES>
<LINE>Provider Pin</LINE>
<LINE>TerminalID: 993324</LINE>
<LINE>Date: 29.06.2018</LINE>
<LINE>TimeOfDay: 15:06:SS</LINE>
<LINE>Trace-No: 160537</LINE>
<LINE>Receipt-No: 475514</LINE>
<LINE>--------------------------------------------------</LINE>
<LINE>Value: 500 QAR</LINE>
<LINE>Product without VAT</LINE>
<LINE>Service: 7736737741</LINE>
<LINE>Hotline: 0110/400773</LINE>
<LINE>Serial Number: 778617719</LINE>
<LINE>CashCode:</LINE>
<LINE>2866-8195-3923-8894</LINE>
</RECEIPT>
<RESULT>0</RESULT>
<RESULTTEXT>Transaction Successful</RESULTTEXT>
<PINCREDENTIALS>
<PIN>2846-4607-1987-3562</PIN>
<SERIAL>778617719</SERIAL>
<VALIDTO>11/29/2018 3:33:34 PM</VALIDTO>
</PINCREDENTIALS>
For this i have created two one main class and two nested class, one nested class with list of string derived class as shown below
[XmlRoot("RESPONSE", DataType = "PRINT")]
public class PinDirectResponseVM
{
public int TERMINALID { get; set; }
public string LOCALDATETIME { get; set; }
public string SERVERDATETIME { get; set; }
public int TXID { get; set; }
public string HOSTTXID { get; set; }
public string AMOUNT { get; set; }
public string CURRENCY { get; set; }
public string LIMIT { get; set; }
[XmlArrayItem(ElementName = "LINE")]
public ReceiptResponseVM RECEIPT { get; set; }
public string RESULT { get; set; }
public string RESULTTEXT { get; set; }
public string AID { get; set; }
public PinCredentialsResponseVM PINCREDENTIALS { get; set; }
}
public class ReceiptResponseVM : List<string>
{
public int LINES { get; set; }
}
public class PinCredentialsResponseVM
{
public string PIN { get; set; }
public string SERIAL { get; set; }
public string VALIDTO { get; set; }
}
When i returning 'PinDirectResponseVM' object not getting <LINES>14<LINES> tag,i getting response like this
<RESPONSE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TERMINALID>993324</TERMINALID>
<LOCALDATETIME>2018-11-16 09:08:40</LOCALDATETIME>
<SERVERDATETIME>6/29/2018 3:33:34 PM</SERVERDATETIME>
<TXID>880034435</TXID>
<HOSTTXID>ID00008769249</HOSTTXID>
<AMOUNT>500</AMOUNT>
<CURRENCY>634</CURRENCY>
<LIMIT>0</LIMIT>
<RECEIPT>
<LINE>Provider Pin</LINE>
<LINE>TerminalID: 993324</LINE>
<LINE>Date: 29.06.2018</LINE>
<LINE>TimeOfDay: 15:06:SS</LINE>
<LINE>Trace-No: 160537</LINE>
<LINE>Receipt-No: 475514</LINE>
<LINE>--------------------------------------------------</LINE>
<LINE>Value: 500 QAR</LINE>
<LINE>Product without VAT</LINE>
<LINE>Service: 7736737741</LINE>
<LINE>Hotline: 0110/400773</LINE>
<LINE>Serial Number: 778617719</LINE>
<LINE>CashCode:</LINE>
<LINE>2866-8195-3923-8894</LINE>
</RECEIPT>
<RESULT>0</RESULT>
<RESULTTEXT>Transaction Successful</RESULTTEXT>
<PINCREDENTIALS>
<PIN>2846-4607-1987-3562</PIN>
<SERIAL>778617719</SERIAL>
<VALIDTO>11/29/2018 3:33:34 PM</VALIDTO>
</PINCREDENTIALS>
So please help me to get the response as per my requirement, what's the best way to generate XML for it?
This is because there are two different child nodes in <RECEIPT></RECEIPT> node which are
<LINES></LINES>
<LINE></LINE>
You can do something like this:
XmlRoot("RESPONSE", DataType = "PRINT")]
public class PinDirectResponseVM
{
public int TERMINALID { get; set; }
public string LOCALDATETIME { get; set; }
public string SERVERDATETIME { get; set; }
public int TXID { get; set; }
public string HOSTTXID { get; set; }
public string AMOUNT { get; set; }
public string CURRENCY { get; set; }
public string LIMIT { get; set; }
public ReceiptResponseVM RECEIPT { get; set; }
public string RESULT { get; set; }
public string RESULTTEXT { get; set; }
public string AID { get; set; }
public PinCredentialsResponseVM PINCREDENTIALS { get; set; }
}
public class ReceiptResponseVM //: List<string>
{
[XmlElement(Order = 1, ElementName = "LINES")]
public int LINES { get; set; }
[XmlElement(Order = 2, ElementName = "LINE")]
public List<string> LINE {get; set;}
}
public class PinCredentialsResponseVM
{
public string PIN { get; set; }
public string SERIAL { get; set; }
public string VALIDTO { get; set; }
}
I'm trying to Deserialize some json using JsonConver.DeserializeObject. however it's not working on some json from the api I'm using. here is a link that does not work: https://api.pokemontcg.io/v1/cards?setCode=smp
and here is a link that does work. https://api.pokemontcg.io/v1/cards?setCode=sm2
I'm not sure why it sometimes works and sometimes not. The data that comes out of it is very similar to each other, just different cards.
Here is the code:
public static async Task<T> GetDataAsync<T>(this HttpClient client, string address, string querystring)
where T : class
{
var uri = address;
if (!string.IsNullOrEmpty(querystring))
{
uri += querystring;
}
var httpMessage = await client.GetStringAsync(uri);
var jsonObject = JsonConvert.DeserializeObject<T>(httpMessage);
return jsonObject;
}
Now my card class
namespace CardAppReal.Lib.Models
{
public class Card
{
public string id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string supertype { get; set; } // if pokemon, trainer or energy
public string setcode { get; set; }
public int number { get; set; }
public string set { get; set; }
}
}
With a root
using System.Collections.Generic;
using CardAppReal.Lib.Models;
namespace CardAppReal.Lib.Entities
{
public class RootCard
{
public List<Card> cards { get; set; }
}
}
If u could help me out I would find it amazing.
I have tested your json.
this is the Model
namespace Test
{
public class Attack
{
public List<string> cost { get; set; }
public string name { get; set; }
public string text { get; set; }
public string damage { get; set; }
public int convertedEnergyCost { get; set; }
}
public class Weakness
{
public string type { get; set; }
public string value { get; set; }
}
public class Resistance
{
public string type { get; set; }
public string value { get; set; }
}
public class Ability
{
public string name { get; set; }
public string text { get; set; }
public string type { get; set; }
}
public class Card
{
public string id { get; set; }
public string name { get; set; }
public int nationalPokedexNumber { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string subtype { get; set; }
public string supertype { get; set; }
public string hp { get; set; }
public List<string> retreatCost { get; set; }
public string number { get; set; }
public string artist { get; set; }
public string rarity { get; set; }
public string series { get; set; }
public string set { get; set; }
public string setCode { get; set; }
public List<string> types { get; set; }
public List<Attack> attacks { get; set; }
public List<Weakness> weaknesses { get; set; }
public List<Resistance> resistances { get; set; }
public string evolvesFrom { get; set; }
public Ability ability { get; set; }
public List<string> text { get; set; }
}
public class RootObject
{
public List<Card> cards { get; set; }
}
}
And this is how I call the Deserialize
RootObject root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(RootObject.WRONG_JSON);
(NB WRONG_JSON is your json string...)
I am using .net to call to a webservice then parse it to usable data.
Right now I am experimenting with this call: http://www.reddit.com/r/all.json
Which returns: http://pastebin.com/AbV4yVuC
This is put in to a string, which I called jsontxt.
I am using JSON.NET to parse the information but it doesn't seem to be working. I initially tried to deserialize it as an object and it didn't work as nothing is put in to the variable
Then I tried to deserialize it as a dataset and I'm having no luck again. My error was
An unhandled exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll
MY CODE:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tutorialresult1
{
class Program
{
static void Main(string[] args)
{
using (var webClient = new System.Net.WebClient())
{
var jsontxt = webClient.DownloadString("http://www.reddit.com/r/all.json");
// Console.Write(json);
// -----Deserializing by Object--------------
//MediaEmbed account = JsonConvert.DeserializeObject<MediaEmbed>(jsontxt);
//Console.WriteLine(account.width); //COMES OUT TO NULL
// -----Deserializing by DataSet--------------
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(jsontxt);
DataTable dataTable = dataSet.Tables["Children"];
Console.WriteLine(dataTable.Rows.Count);
}
}
public class MediaEmbed
{
public string content { get; set; }
public int width { get; set; }
public bool scrolling { get; set; }
public int height { get; set; }
}
.... //rest of classes here for each json which were generated with http://json2csharp.com/
}
}
I'm just trying to make the JSON easily accessible by parsing it.
Using json2charp I generated the following set of classes. Using those you should be able to deserialize the JSON into RootObject using JSON.NET.
var account = JsonConvert.DeserializeObject<RootObject>(jsontxt);
.
public class MediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public string url { get; set; }
public string type { get; set; }
public string author_name { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public int thumbnail_width { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public int thumbnail_height { get; set; }
public string author_url { get; set; }
}
public class SecureMedia
{
public Oembed oembed { get; set; }
public string type { get; set; }
}
public class SecureMediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed2
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public int thumbnail_width { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public string type { get; set; }
public int thumbnail_height { get; set; }
public string url { get; set; }
public string author_name { get; set; }
public string author_url { get; set; }
}
public class Media
{
public string type { get; set; }
public Oembed2 oembed { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public string selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public SecureMedia secure_media { get; set; }
public string link_flair_text { get; set; }
public string id { get; set; }
public int gilded { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public Media media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public string link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public string after { get; set; }
public object before { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
You are trying to deserialize a json-string into a dataset-object. But the json-string doesn't have the format of a dataset. So you need to create a class which matches the json or deserialize it into a dictionary or sth. like this.
Have you tried deserialize using the following? Seems to be more robust for me.
using System.Web.Script.Serialization;
...
var x = new JavaScriptSerializer().Deserialize<Obj_type>(jsonstring);
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
as purplej0kr mentioned you will need to have a .Net model to use for Obj_type (and it will need to match the object you are parsing) or this will not work.
You will need the System.Web.Extensions.dll referenced in your project (right click add reference, dll is usually under 'Assemblies'). Otherwise:
Where can I find the assembly System.Web.Extensions dll?
Guyz
I am trying to parse a JSON string into object. I have the below entity in which I am parsing the JSON string
public class Room : BaseEntity
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public List<RoomImage> RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
//public List<Equipment> Equipment { get; set; }
public override string ToString()
{
return this.Name;
}
}
public class RoomImage : BaseEntity
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
}
public class InternalOnly : BaseEntity
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class BaseEntity
{
}
I am using below method to parse the string into object
public static T ParseObjectToJSON<T>(string responseText)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText)))
{
var rootObject = serializer.ReadObject(stream);
//return Convert.ChangeType(rootObject,typeof(T),System.Globalization.CultureInfo.CurrentCulture.TextInfo);
return (T)rootObject;
}
}
Below is the JSON string which I am trying to parse
https://docs.google.com/document/d/1k81M_UxIrXpHUPQNDUCHDfNw1wY7LM4mAaXjwpYMshk/edit?usp=sharing
The below json string is working
https://docs.google.com/document/d/1uQNwMmSyEZSolyxUVJl6gXzZPr6aRAf_WAogmUvVqt4/edit?usp=sharing
While parsing I get below error
The data contract type 'GAP.Entities.Room' cannot be deserialized because the member 'RoomImage' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.
Note- RoomImage is marked public in the entity class. I get this error only when JSON string contains RoomImage array string otherwise no erro.
Any help is highly appreciated.
Thanks
Vinod
You can download and deserialize an JSON using Newtonsoft.
You have to reference the following DLL, and after that you can try this:
List<Room> deserializedObj = (List<Room>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, typeof(List<Room>));
The problem with your json is that if RoomImage has a single element, your service returns it as an object {} not as an array of objects [{}].
So If you want to use type-safe classes in your code(since dynamically accessing is also possible) you should pre-process your json before deserializing. Below code works (of course, as everybody says, using Json.Net)
string json = your__json__string
//PreProcess
var jobj = JObject.Parse(json);
foreach (var j in jobj["ObjectList"])
{
if (!(j["RoomImage"] is JArray))
{
j["RoomImage"] = new JArray(j["RoomImage"]);
}
}
var obj = JsonConvert.DeserializeObject<RootObject>(jobj.ToString());
public class InternalOnly
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class RoomImage
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdateDate { get; set; }
public string LastUpdateId { get; set; }
}
public class ObjectList
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public RoomImage[] RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public string IsRestrictedRoom { get; set; }
public InternalOnly InternalOnly { get; set; }
public object Equipment { get; set; }
}
public class RootObject
{
public List<ObjectList> ObjectList { get; set; }
}
The property RoomImage is public but your class probably isn't.
Make sure the RoomImage class is also marked public. That should solve the problem.
Alternatively use a library like JSON.NET that can do this deserialization without the need for public classes.