Deserialize array in xml C# - c#

i have this Xml
<Facility ID="353">
<Name>Test</Name>
<Buildingtype>Test</Buildingtype>
<SMSInfoID>
<ID default="True">140</ID>
<ID default="True">140</ID>
<ID default="True">140</ID>
</SMSInfoID>
</Facility>
i have problem with desializing tag
I have tried many ways to solve it, and its what the last i have tested but still cannot reach the data inside this element.
public class Facility
{
[XmlAttribute("ID"), Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[XmlElement("Buildingtype")]
public string CategoryID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("SMSInfoID")]
public virtual SMSInfoID SMSInfoID { get; set; }
}
[XmlRoot("SMSInfoID")]
public class SMSInfoID
{
[XmlIgnore, Key]
public int Id { get; set; }
[XmlElement("ID")]
public List<ID> ID { get; set; }
}
[XmlRoot("ID")]
public class ID
{
[Key]
public int Id { get; set; }
[XmlAttribute("default")]
public string Default { get; set; }
}
Can any one help me to solve this.

DO NOT USE ARRAY WITH YOUR XML. The array adds a extra level of tags.
the code below matches you xml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Facility facility = new Facility() {
Id = 353,
Name = "Test",
CategoryID = "Test",
SMSInfoID = new SMSInfoID() {
ID = new List<ID>() {
new ID() { _default = true, value = 140},
new ID() { _default = true, value = 140},
new ID() { _default = true, value = 140}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Facility));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, facility);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
public class Facility
{
[XmlAttribute("ID")]
public int Id { get; set; }
[XmlElement("Buildingtype")]
public string CategoryID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("SMSInfoID")]
public virtual SMSInfoID SMSInfoID { get; set; }
}
[XmlRoot("SMSInfoID")]
public class SMSInfoID
{
[XmlElement("ID")]
public List<ID> ID { get; set; }
}
[XmlRoot("ID")]
public class ID
{
[XmlAttribute("default")]
public Boolean _default {get; set;}
[XmlText()]
public int value { get; set; }
}
}

If you are not using the Id of SMSInfoID, you can rewrite it as a property of Facility:
[XmlArray("SMSInfoID")]
[XmlArrayItem("ID")]
public List<ID> ID { get; set; }
or wrap this property for XML:
[XmlArray("SMSInfoID")]
[XmlArrayItem("ID")]
public List<ID> ID
{
get {return SMSInfoID.ID;}
set {SMSInfoID.ID = value;
}
[XmlIgnore]
public virtual SMSInfoID SMSInfoID { get; set; }
If that's not a possibility, what can/are you allowed to change?

Add attribute XmlText to property Id to your class ID:
[XmlRoot("ID")]
public class ID
{
[XmlText, Key] // <-- here
public int Id { get; set; }
[XmlAttribute("default")]
public string Default { get; set; }
}

Related

XML Serialization Not populating the array

I am trying to serialize the below XML. But the section "Keys" are not getting populated and its coming as null in the serialized object.
<?xml version="1.0"?>
<Golden>
<SecType>
<ID>New</ID>
<Count>1</Count>
</SecType>
<Request>
<Action>New</Action>
<Keys>
<Key>
<ReferenceType>AAA</ReferenceType>
<ReferenceValue>1111</ReferenceValue>
<Description></Description>
</Key>
<Key>
<ReferenceType>BBBB</ReferenceType>
<ReferenceValue>22222</ReferenceValue>
<Description></Description>
</Key>
</Keys>
</Request></Golden>
I am trying to create a custom class object for further use. Please see my code below.
[Serializable]
[XmlRootAttribute("Golden")]
public class Process
{
[XmlElementAttribute("SecType")]
public SecType secType { get; set; }
[XmlElementAttribute("Request")]
public Request request { get; set; }
}
[Serializable]
[XmlRootAttribute("SecType")]
public class SecType
{
[XmlElementAttribute("ID")]
public string ID { get; set; }
[XmlElementAttribute("Count")]
public int Count { get; set; }
}
[Serializable]
[XmlRootAttribute("Request")]
public class Request
{
[XmlElementAttribute("Action")]
public string Action { get; set; }
[XmlElementAttribute("Keys")]
public Keys keys { get; set; }
}
[Serializable()]
[XmlRootAttribute("Keys")]
public class Keys
{
[XmlArray("Keys")]
[XmlArrayItem("Key", typeof(Key))]
public Key[] key { get; set; }
}
[Serializable]
[XmlRootAttribute("Key")]
public class Key
{
[XmlElementAttribute("ReferenceType")]
public string ReferenceType { get; set; }
[XmlElementAttribute("ReferenceValue")]
public string ReferenceValue { get; set; }
[XmlElementAttribute("Description")]
public string Description { get; set; }
}
string sPath = #"C:\Test\ConsoleApp1\test.xml";
Process proc = new Process();
XmlSerializer serializer = new XmlSerializer(typeof(Process));
StreamReader reader = new StreamReader(sPath);
proc = (Process)serializer.Deserialize(reader);
reader.Close();
I mainly referred this. But it's not working in my implementation.Thanks for you help
I just fixed the Key Element :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication142
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Process));
Process proc = (Process)serializer.Deserialize(reader);
}
}
[Serializable]
[XmlRootAttribute("Golden")]
public class Process
{
[XmlElementAttribute("SecType")]
public SecType secType { get; set; }
[XmlElementAttribute("Request")]
public Request request { get; set; }
}
[Serializable]
[XmlRootAttribute("SecType")]
public class SecType
{
[XmlElementAttribute("ID")]
public string ID { get; set; }
[XmlElementAttribute("Count")]
public int Count { get; set; }
}
[Serializable]
[XmlRootAttribute("Request")]
public class Request
{
[XmlElementAttribute("Action")]
public string Action { get; set; }
[XmlArray("Keys")]
[XmlArrayItem("Key")]
public Key[] keys { get; set; }
}
[Serializable]
[XmlRootAttribute("Key")]
public class Key
{
[XmlElementAttribute("ReferenceType")]
public string ReferenceType { get; set; }
[XmlElementAttribute("ReferenceValue")]
public string ReferenceValue { get; set; }
[XmlElementAttribute("Description")]
public string Description { get; set; }
}
}

Xml deserialization returns empty array even though POCO has right xml attributes generated from xsd2code++ tool

I am using XSD2Code++ 2019 tool for visual studio to generate POCOs from aset of 5 xsds. I have added the POCO class below. I see that it has the right xml decorators for it to serialize properly. But I really fail to understand or figure out why the 3rd level object in the returned deserialized data is always empty and not typecasted to the correct type.
I have tried changing attributes to xmlArray and xmlArrayElement too but none of that worked.
POCO class-
https://gist.github.com/nimisha84/b86a4bb2bf37aea6ec351a9f6e331bed
Sample xml response which has null values after deserialization using c# code-
<?xml version="1.0" encoding="UTF-8"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2019-07-05T14:29:08.603-07:00">
<QueryResponse startPosition="1" maxResults="1" totalCount="1">
<Invoice domain="QBO" sparse="false">
<Id>8633</Id>
<SyncToken>14</SyncToken>
<MetaData>
<CreateTime>2019-01-09T11:32:12-08:00</CreateTime>
<LastUpdatedTime>2019-06-05T12:49:40-07:00</LastUpdatedTime>
</MetaData>
<CustomField>
<DefinitionId>1</DefinitionId>
<Name>CustomPO</Name>
<Type>StringType</Type>
<StringValue>Gold</StringValue>
</CustomField>
<DocNumber>2830</DocNumber>
<TxnDate>2019-01-09</TxnDate>
<CurrencyRef name="United States Dollar">USD</CurrencyRef>
<ExchangeRate>1</ExchangeRate>
<PrivateNote>Voided - Voided</PrivateNote>
<Line>
<Id>1</Id>
<LineNum>1</LineNum>
<Description>Description</Description>
<Amount>0</Amount>
<DetailType>SalesItemLineDetail</DetailType>
<SalesItemLineDetail>
<ItemRef name="Name27140">815</ItemRef>
<Qty>0</Qty>
<TaxCodeRef>NON</TaxCodeRef>
</SalesItemLineDetail>
</Line>
<Line>
<Amount>0</Amount>
<DetailType>SubTotalLineDetail</DetailType>
<SubTotalLineDetail />
</Line>
<TxnTaxDetail>
<TotalTax>0</TotalTax>
</TxnTaxDetail>
<CustomerRef name="a4">2561</CustomerRef>
<DueDate>2019-01-09</DueDate>
<TotalAmt>0</TotalAmt>
<HomeTotalAmt>0</HomeTotalAmt>
<ApplyTaxAfterDiscount>false</ApplyTaxAfterDiscount>
<PrintStatus>NeedToPrint</PrintStatus>
<EmailStatus>NotSet</EmailStatus>
<Balance>0</Balance>
<Deposit>0</Deposit>
<AllowIPNPayment>false</AllowIPNPayment>
<AllowOnlinePayment>false</AllowOnlinePayment>
<AllowOnlineCreditCardPayment>false</AllowOnlineCreditCardPayment>
<AllowOnlineACHPayment>false</AllowOnlineACHPayment>
</Invoice>
</QueryResponse>
</IntuitResponse>
Code to deserialize-
string responseText = apiResponse.ReadToEnd();
var responseSerializer = new XmlObjectSerializer();
IntuitResponse restResponse =
(IntuitResponse)this.responseSerializer.Deserialize<IntuitResponse>(responseText);
res=restResponse.Items[0] as QueryResponse;
here QueryResponse is not having Invoice(of type IntuitEntity) object returned. Instead empty value is returned. See screenshot.
https://imgur.com/a/5yF6Khb
I really need help to figure out why the 3rd level property is returned as empty.
I tested code below and it works. I manually generated the classes which produces simpler results than using tools.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string responseText = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(responseText);
XmlReader xReader = XmlReader.Create(reader);
XmlSerializer serializer = new XmlSerializer(typeof(IntuitResponse));
IntuitResponse response = (IntuitResponse)serializer.Deserialize(xReader);
}
}
[XmlRoot(ElementName = "IntuitResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public class IntuitResponse
{
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlElement(ElementName = "QueryResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public QueryResponse response { get; set; }
}
public class QueryResponse
{
[XmlAttribute("startPosition")]
public int startPosition { get; set; }
[XmlAttribute("maxResults")]
public int maxResults { get; set; }
[XmlAttribute("totalCount")]
public int totalCount { get; set; }
[XmlElement(ElementName = "Invoice", Namespace = "http://schema.intuit.com/finance/v3")]
public Invoice invoice { get; set; }
}
public class Invoice
{
[XmlAttribute("domain")]
public string domain { get; set; }
[XmlAttribute("sparse")]
public Boolean sparse { get; set; }
public int Id { get; set; }
public int SyncToken { get; set; }
[XmlElement(ElementName = "MetaData", Namespace = "http://schema.intuit.com/finance/v3")]
public MetaData metaData { get; set; }
[XmlElement(ElementName = "CustomField", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomField customField { get; set; }
public int DocNumber { get; set; }
public DateTime TxnDate { get; set; }
[XmlElement(ElementName = "CurrencyRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CurrencyRef currencyRef { get; set; }
public int ExchangeRate { get; set; }
public string PrivateNote { get; set; }
[XmlElement(ElementName = "Line", Namespace = "http://schema.intuit.com/finance/v3")]
public List<Line> line { get; set; }
[XmlElement(ElementName = "TxnTaxDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public TxnTaxDetail txnTaxDetail { get; set; }
[XmlElement(ElementName = "CustomerRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomerRef CustomerRef { get; set; }
public DateTime DueDate { get; set; }
public int TotalAmt { get; set; }
public int HomeTotalAmt { get; set; }
public Boolean ApplyTaxAfterDiscount { get; set; }
public string PrintStatus { get; set; }
public string EmailStatus { get; set; }
public int Balance { get; set; }
public int Deposit { get; set; }
public Boolean AllowIPNPayment { get; set; }
public Boolean AllowOnlinePayment { get; set; }
public Boolean AllowOnlineCreditCardPayment { get; set; }
public Boolean AllowOnlineACHPayment { get; set; }
}
public class MetaData
{
public DateTime CreateTime { get; set; }
public DateTime LastUpdatedTime { get; set; }
}
public class CustomField
{
public int DefinitionId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string StringValue { get; set; }
}
public class CurrencyRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class Line
{
public int Id { get; set; }
public int LineNum { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string DetailType { get; set; }
[XmlElement(ElementName = "SalesItemLineDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public SalesItemLineDetail salesItemLineDetail { get; set; }
}
public class CustomerRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class SalesItemLineDetail
{
[XmlElement(ElementName = "ItemRef", Namespace = "http://schema.intuit.com/finance/v3")]
public ItemRef itemRef { get; set; }
public int Qty { get; set; }
public string TaxCodeRef { get; set; }
}
public class ItemRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class TxnTaxDetail
{
public int TotalTax { get; set; }
}
}

XML File convert to C# object

I have to read this XML File in a C# Object. That i have these information in an Object. Not all tags are important!
These would be the important information i need in the Object:
- Alignment with the staStart Property
- CoordGoem with Line Spiral and Curve inside and of thesse are only the properties important
XML File
<Alignments name="">
<Alignment name="AL-voor omvorming landxml" length="6550.000000000015" staStart="30000." desc="">
<CoordGeom>
<Line dir="0." length="100.">
<Start>175.282796686952 -1708.474133524573</Start>
<End>175.282796686952 -1608.474133524573</End>
</Line>
<Spiral length="100." radiusEnd="500." radiusStart="INF" rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>175.282796686952 -1608.474133524573</Start>
<PI>175.282796686952 -1541.772512759896</PI>
<End>171.951843548555 -1508.574087238959</End>
</Spiral>
<Curve rot="cw" chord="99.833416646828" crvType="arc" delta="11.459155902616" dirEnd="342.811266146075" dirStart="354.270422048692" external="2.510459200228" length="100." midOrd="2.497917360987" radius="500." tangent="50.167336042725">
<Start>171.951843548555 -1508.574087238959</Start>
<Center>-325.550239090457 -1558.490795562373</Center>
<End>152.118005472345 -1410.730692231703</End>
<PI>166.94346698734 -1458.657378915545</PI>
</Curve>
<Spiral length="100." radiusEnd="INF" radiusStart="500." rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>152.118005472345 -1410.730692231703</Start>
<PI>142.257940647353 -1378.855783172596</PI>
<End>116.283106059873 -1317.419522049479</End>
</Spiral>
Object
public class LandXMLAlignments
{
public long staStart { get; set; }
[XmlArray("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
I would have drawn this object from it but i don't now how i actually read the xml file in this Object.
Assuming your classes are ok you could just create a helper class to perfom transformations from XML to a POCO object like this:
public static class XmlHelper
{
public static T ParseXmlFile<T>(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(filePath))
{
T configuration = (T)serializer.Deserialize(reader);
return configuration;
}
}
}
And use it like this:
var alignments = XmlHelper.ParseXmlFile<LandXMLAlignments>(YourXMLPath);
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Alignments));
Alignments alignments = (Alignments)serializer.Deserialize(reader);
}
}
public class Alignments
{
[XmlElement("Alignment")]
public Alignment alignment { get; set; }
}
public class Alignment
{
public long staStart { get; set; }
[XmlElement("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
[XmlElement("Line")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
[XmlElement("Spiral")]
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
[XmlElement("Curve")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
}
If you are using Visual studio, then do the following:
Copy XML
Select Edit Menu,
Paste Special, Paste XML as Classes.
Reference

Batch Data Extraction Script

apologies for the newbie question as I am very new to the world of programming etc.
I have a large XML file containing (see link below). It contains an ID number for legal entities (LEI) followed by the ID for their respective parent company.
Example from the XML file
The yellow is the entity LEI number and the green is the parent company LEI.
I would like to create some sort of batch script or GUI so I can enter a list of entity (green) LEI numbers and then given an output of all the corresponding parent LEI numbers.
Here is the file for anyone wondering: https://leidata.gleif.org/api/v1/concatenated-files/rr/20171025/zip
I am very inexperienced so I am not sure where to start.
Many thanks
Copy the entire file content to clipboard, then open your visual studio project and go to menu -> edit -> paste special -> paste as xml classes. This will generate a bunch of classes in the file you have currently open. Save this file. Then you use this code to load the file and return the loaded data:
public static RelationshipData LoadFile(string fileName)
{
var serializer = new XmlSerializer(typeof(Items));
RelationshipData data;
using (Stream r = new FileStream(filename, FileMode.Open))
{
data = (RelationshipData)serializer.Deserialize(r);
}
return data;
}
Now you should be able to access the file content using the properties of the returned data object. Haven't used this method with xml-data that uses prefixes, but I think this will be handled too...
With this data you should build up a dictionary or something like that that suits your needs that maps one ID to the other ID.
You should really start reading why and how this works...
NOT TESTED
I think I got most of the elements. You need to do some careful checking since there are a lot of nodes. I added a writer so I can use Beyond Compare to check if I got all the nodes. Fixed some errors. Still need some minor tweaks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.xml";
const string OUTPUT_FILENAME = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
XmlReader reader = XmlReader.Create(INPUT_FILENAME, settings);
XmlSerializer serializer = new XmlSerializer(typeof(RelationshipDataRelationshipData));
RelationshipDataRelationshipData relationshipDataRelationshipData = (RelationshipDataRelationshipData)serializer.Deserialize(reader);
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME, wSettings);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("rr", "http://www.gleif.org/data/schema/rr/2016");
ns.Add("gleif", "http://www.gleif.org/concatenated-file/header-extension/2.0");
serializer.Serialize(writer, relationshipDataRelationshipData, ns);
writer.Flush();
writer.Close();
}
}
[XmlRoot(ElementName = "RelationshipData", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipDataRelationshipData
{
[XmlElement("Header")]
public Header header { get; set; }
[XmlElement("RelationshipRecords", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public RelationshipRecords relationshipRecords { get; set; }
}
[XmlRoot(ElementName = "Header", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class Header
{
[XmlElement("ContentDate")]
public DateTime ContentDate { get; set; }
[XmlElement("FileContent")]
public string FileContent { get; set; }
[XmlElement("RecordCount")]
public int RecordCount { get; set; }
[XmlElement("Extension", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public Extension extension { get; set; }
}
[XmlRoot(ElementName = "Extension", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class Extension
{
[XmlElement(ElementName = "Sources", Namespace = "http://www.gleif.org/concatenated-file/header-extension/2.0")]
public Sourses sources { get; set; }
}
[XmlRoot(ElementName = "Sources", Namespace = "http://www.gleif.org/concatenated-file/header-extension/2.0")]
public class Sourses
{
[XmlElement("Source")]
public List<Source> source { get; set; }
}
[XmlRoot(ElementName = "Source", Namespace = "http://www.gleif.org/concatenated-file/header-extension/2.0")]
public class Source
{
[XmlElement("ContentDate")]
public DateTime ContentDate { get; set; }
[XmlElement("Originator")]
public string Originator { get; set; }
[XmlElement("RecordCount")]
public int RecordCount { get; set; }
}
[XmlRoot(ElementName = "RelationshipRecords", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipRecords
{
[XmlElement("RelationshipRecord")]
public List<RelationshipRecord> relationshipRecord { get; set; }
}
[XmlRoot(ElementName = "RelationshipRecord", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipRecord
{
[XmlElement("Relationship")]
public Relationship relationship { get; set; }
[XmlElement("Registration")]
public Registration registration { get; set; }
[XmlElement("Extension", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public Extension extension { get; set; }
}
[XmlRoot(ElementName = "Relationship", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class Relationship
{
[XmlElement("StartNode")]
public Node StartNode { get; set; }
[XmlElement("EndNode")]
public Node EndNode { get; set; }
public string RelationshipType { get; set; }
[XmlElement("RelationshipPeriods")]
public RelationshipPeriods relationshipPeriods { get; set; }
public string RelationshipStatus { get; set; }
[XmlElement("RelationshipQualifiers")]
public RelationshipQualifiers relationshipQualifiers { get; set; }
}
[XmlRoot(ElementName = "Node", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class Node
{
public string NodeID { get; set; }
public string NodeIDType { get; set; }
}
[XmlRoot(ElementName = "class RelationshipQualifiers", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipQualifiers
{
[XmlElement("RelationshipQualifier")]
public RelationshipQualifier relationshipQualifier { get; set; }
}
[XmlRoot(ElementName = "class RelationshipQualifier", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipQualifier
{
public string QualifierDimension { get; set; }
public string QualifierCategory { get; set; }
}
[XmlRoot(ElementName = "Registration", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class Registration
{
public DateTime InitialRegistrationDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public string RegistrationStatus { get; set; }
public DateTime NextRenewalDate { get; set; }
public string ManagingLOU { get; set; }
public string ValidationSources { get; set; }
public string ValidationDocuments { get; set; }
}
[XmlRoot(ElementName = "class RelationshipPeriods", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipPeriods
{
[XmlElement("RelationshipPeriod")]
public List<RelationshipPeriod> relationshipPeriod { get; set; }
}
[XmlRoot(ElementName = "class RelationshipPeriod", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipPeriod
{
[XmlElement("StartDate")]
public DateTime StartDate { get; set; }
[XmlElement("EndDate")]
public DateTime EndDate { get; set; }
[XmlElement("PeriodType")]
public string PeriodType { get; set; }
}
[XmlRoot(ElementName = "class RelationshipQuantifiers", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipQuantifiers
{
[XmlElement("RelationshipQuantifier")]
public List<RelationshipQuantifier> relationshipQuantifier { get; set; }
}
[XmlRoot(ElementName = "class RelationshipQuantifier", Namespace = "http://www.gleif.org/data/schema/rr/2016")]
public class RelationshipQuantifier
{
[XmlElement("MeasurementMethod")]
public DateTime MeasurementMethod { get; set; }
[XmlElement("QuantifierAmount")]
public decimal QuantifierAmount { get; set; }
[XmlElement("QuantifierUnits")]
public string QuantifierUnits { get; set; }
}
}

Json.Net serialise collection into named attributes

I am creating a Xamarin app with API calls managed by Refit and other Paul Betts libraries and was looking at serialising a collection of objects into a Json attributed array.
The question I have is how do I serialise the collection of MemberSlot objects in the MemberBooking type, using Json.Net, into the desired Json?
The names of the objects will always be numbers 1 -> 4 but some or all may not be present.
Question
Could I just change the List property in the MemberBooking object to a Dictionary and populate the string key appropriately?
Object heirarchy
public class MemberBookingRequest
{
[JsonProperty("member_booking_request")]
public MemberBooking Booking { get; set; }
}
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public List<MemberSlot> Slots { get; set; }
}
public class MemberSlot
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("type")]
public BookingType Type { get; set; }
[JsonProperty("holes")]
public int Holes { get; set; }
[JsonProperty("user_id")]
public int MemberId { get; set; }
}
Current Json
{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":[
{
"type":"Member",
"holes":18,
"user_id":110
},
{
"type":"Member",
"holes":18,
"user_id":111
},
{
"type":"Member",
"holes":18,
"user_id":112
},
{
"type":"Member",
"holes":18,
"user_id":117
]
}
}
}
Desired Json
{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":{
"1":{
"type":"Member",
"holes":18,
"user_id":110
},
"2":{
"type":"Member",
"holes":18,
"user_id":111
},
"3":{
"type":"Member",
"holes":18,
"user_id":112
},
"4":{
"type":"Member",
"holes":18,
"user_id":117
}
}
}
}
You'll have to change the way you create Slots property. Assign MemberSlot.Id as key, MemberSlot itself as value when filling Slots dictionary.
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public Dictionary<int,MemberSlot> Slots { get; set; }
}
This sample will give the your desired json output,using a dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace jsonconversion
{
public class Program
{
public static void Main(string[] args)
{
Dictionary<int,MemberSlot> slots=new Dictionary<int, MemberSlot>();
MemberSlot slot1 = new MemberSlot() {Id = 1, Holes =2, MemberId = 1};
slots.Add(1,slot1);
MemberBookingRequest mbr = new MemberBookingRequest
{
Booking = new MemberBooking()
{CourseId = 1, TeeDate ="",TeeTime = "",Slots = slots}
};
string jd = JsonConvert.SerializeObject(mbr);
Console.WriteLine(jd);
}
}
public class MemberBookingRequest
{
[JsonProperty("member_booking_request")]
public MemberBooking Booking { get; set; }
}
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public Dictionary<int, MemberSlot> Slots { get; set; }
}
public class MemberSlot
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("holes")]
public int Holes { get; set; }
[JsonProperty("user_id")]
public int MemberId { get; set; }
}
}

Categories