I'm getting XML in following format:
<Order>
<OrderData>
<OfferOrder></OfferOrder>
<OfferOrder></OfferOrder>
</OrderData>
</Order>
Now when I'm Deserializng string orderxml containing the XML, It doesn't fill <OfferOrder> into my OrderData object.
XmlSerializer xmlserializer = new XmlSerializer((typeof(Order)));
using (TextReader reader = new StringReader(orderxml))
{
order = (Order)xmlserializer.Deserialize(reader);
}
Classes:
public partial class Order
{
private OrderOrderData orderDataField;
public OrderOrderData OrderData
{
get
{
return this.orderDataField;
}
set
{
this.orderDataField = value;
}
}
}
public partial class OrderOrderData
{
private OrderOrderDataOfferOrder[] offerOrderField;
public OrderOrderDataOfferOrder[] OfferOrder
{
get
{
return this.offerOrderField;
}
set
{
this.offerOrderField = value;
}
}
}
Is something wrong with my classes?
There are some issues in your code. First you can make your properties to auto-implemented properties, that is omit the private backing-fields and write this instead:
public MyType MyProperty { get; set; }
Second you have to provide the names of the tags within the Xml to the serializer. In your case the names within the xml and those in your class-structure are equal, so you can omit the names also. However just for completeness:
public class Order
{
[XmlElement("OrderData")
public OrderOrderData OrderData { get; set; }
}
public class OrderOrderData
{
[XmlElement("OfferOrder")
public OrderOrderDataOfferOrder[] OfferOrder { get; set; }
}
The reason why it doesn´t work for you is that arrays are usually serialized with a nested element whose name in your case would be OfferOrders. Within that tag you have then the arrays elements. Usually it´s not wanted to have that further nesting, what you want instead is to flatten the elements of the array directly into your actual data-class. To do so add an XmlElement upfront your array-declaration with the name of the elements, in my code OfferOrder.
Related
I have the following test XML string:
<?xml version="1.0" encoding="UTF-8"?>
<test id="myid">
<b>b1</b>
<a>a2</a>
<a>a1</a>
<b>b2</b>
</test>
which I deserialize using this class:
[XmlRoot(ElementName = "test")]
public class Test
{
[XmlElement(ElementName = "a")]
public List<string> A { get; set; }
[XmlElement(ElementName = "b")]
public List<string> B { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
If I'm now going to serialize the object the result will be:
<?xml version="1.0" encoding="utf-16"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="myid">
<a>a2</a>
<a>a1</a>
<b>b1</b>
<b>b2</b>
</test>
Is there a way to keep the initial sort order?
I guess I can't use [XmlElementAttribute(Order = x)] cause the order shouldn't be hardcoded but identically with the initial xml.
I thought about adding an order property to my lists like that
[XmlRoot(ElementName="a")]
public class A
{
[XmlAttribute(AttributeName="order")]
public string Order { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="b")]
public class B
{
[XmlAttribute(AttributeName="order")]
public string Order { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="test")]
public class Test
{
[XmlElement(ElementName="a")]
public List<A> A { get; set; }
[XmlElement(ElementName="b")]
public List<B> B { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
but I don't know how to order by them when serializing.
You can do this with XmlSerializer by using a single collection to capture both the <a> and <b> elements and applying the [XmlElement(Name, Type = typeof(...))] attribute to it multiple times, once for each desired element name. Because you are using a single collection to deserialize both elements, the order is automatically preserved. However, to make this work, XmlSerializer must be able to determine the correct element name when re-serializing. There are two approaches to accomplish this, as documented in Choice Element Binding Support:
If the collection contains polymorphic items, the element name can be mapped to the concrete item type by using the [XmlElementAttribute(String, Type)] constructor. For instance, if you have a sequence of elements that might be strings or integers like so:
<Things>
<string>Hello</string>
<int>999</int>
</Things>
This can be bound to a collection as follows:
public class Things
{
[XmlElement(Type = typeof(string)),
XmlElement(Type = typeof(int))]
public List<object> StringsAndInts { get; set; }
}
If the collection contains only a single type of item, the element name can be encoded in an associated array of enum values, where the enum names correspond to the element names and the array itself is identified via the [XmlChoiceIdentifierAttribute] attribute.
For details, see the documentation examples.
I find option #1 easier to work with than option #2. Using this approach, the following model will deserialize and re-serialize your XML while successfully preserving the order of the <a> and <b> elements:
public abstract class StringElementBase
{
[XmlText]
public string Text { get; set; }
public static implicit operator string(StringElementBase element)
{
return element == null ? null : element.Text;
}
}
public sealed class A : StringElementBase
{
}
public sealed class B : StringElementBase
{
}
[XmlRoot(ElementName = "test")]
public class Test
{
[XmlElement("a", Type = typeof(A))]
[XmlElement("b", Type = typeof(B))]
public List<StringElementBase> Items { get; } = new List<StringElementBase>();
[XmlIgnore]
// For convenience, enumerate through the string values of the items.
public IEnumerable<string> ItemValues { get { return Items.Select(i => (string)i); } }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
Working .Net fiddle.
For more examples of using [XmlChoiceIdentifier] to deserialize a sequence of elements with different names to c# objects of the same type, see for instance here or here.
No, basically; XmlSerializer doesn't support that. If you want to use that option you'd need to write it manually with XDocument or XmlDocument or XmlReader.
Scenario
I have some XML come down from a service that I want to deserialize.
Depending on what is returned from the service, the XML can vary slightly (with the element names); but the XML always follows a common structure.
Here is a sample of what the XML might look like:
<ATemplate>
<Name>SomeTemplate</Name>
<TemplateItems>
<ATemplateItem>
<Name>SomeTemplateItem</Name>
<TemplateFields>
<ATemplateField>
<Name>SomeTemplateField</Name>
<Colour>Blue</Colour>
</ATemplateField>
... more template fields
</TemplateFields>
</ATemplateItem>
... more template items
</TemplateItems>
</ATemplate>
Using the above XML as an example, I have created a ATemplate class that will deserialize nicely from the XML, using the ATemplateItem and ATemplateField classes accordingly:
public class ATemplate
{
public string Name { get; set; }
public List<ATemplateItem> TemplateItems { get; set; }
}
public class ATemplateItem
{
public string Name { get; set; }
public List<ATemplateField> TemplateFields { get; set; }
}
public class ATemplateField
{
public string Name { get; set; }
public string Colour { get; set; }
}
I use this code to deserialize:
ATemplate template;
using (TextReader reader = new StringReader(xmlString))
{
template = (ATemplate)new XmlSerializer(typeof(ATemplate)).Deserialize(reader);
}
All good, so far.
Curveball
The same scenario might occur where the XML contains BTemplate, BTemplateItems and BTemplateFields; still following the structure as above.
So I created other classes for this situation:
public class BTemplate { ... }
public class BTemplateItem { ... }
public class BTemplateField { ... }
And made the relevant classes inherit respectively from ITemplate, ITemplateItem and ITemplateField I created, also:
Interfaces
public class ITemplate
{
public string Name { get; set; }
public List<ITemplateItem> TemplateItems { get; set; }
}
public class ITemplateItem
{
public string Name { get; set; }
public List<ITemplateField> TemplateFields { get; set; }
}
public class ITemplateField
{
public string Name { get; set; }
public string Colour { get; set; }
}
This is so I can then create one function, which is able to loop through the ITemplateItems and their ITemplateFields and perform some cool stuff:
public void Foo(ITemplate template)
{
foreach (var item in template.TemplateItems)
{
// do cool stuff
foreach (var field in item.TemplateFields)
{
// do more cool stuff
}
}
}
Some things to note:
In the object that contains the XML, I know what "type" the XML contains - given an Enum I use to identify
I then use a switch statement to run different methods, depending on the said "type"
Generic Method?
Now, rather than deserializing the XML differently in each of those method cases, I would like to use a Generic method to deserialize.
So I created one, like this:
public ITemplate DeserializeTemplate<T>(string xmlString) where T : ITemplate
{
using (TextReader reader = new StringReader(xmlString))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
}
And call it from within the specific methods like so:
var template = DeserializeTemplate<ATemplate>(xmlString);
Then, I can use the ITemplate that it returns, and pass it to Foo(ITemplate template) to go and perform some magic and wizardry.
But...
No compilation errors, as yet - however I get a RunTime error, because it cannot deserialize an Interface.
I gather this is because it's trying to then deserialize the ITemplate's TemplateItems as ITemplateItems.
Can I do the above?
My question is:
How can I get around this issue?
Can I use this Generic deserialize method?
Will I need to treat each one differently in the separate methods?
Will I need to make the Interface generic also, with the types to expect?
I'm banging my head against the desk, so I really hope you lovely SO people can help.
As always, your comments, answers and suggestions are much appreciated :)
I need to sandwich an element inside of another element. Is it possible to serialize XML like this?
http://pastebin.com/7qDE7Ses
Here is my class
[XmlRoot(ElementName = "SalesOrderMod")]
public partial class SalesOrderMod
{
[XmlElementAttribute(Order = 1)]
public string TxnID { get; set; }
[XmlElementAttribute(Order = 2)]
public string EditSequence { get; set; }
[XmlElementAttribute(Order = 3)]
public string ShipDate { get; set; }
[XmlElementAttribute(Order = 4)]
public ListRef ShipMethodRef = new ListRef();
public bool ShouldSerializeShipMethodRef()
{
return !(String.IsNullOrEmpty(ShipMethodRef.FullName));
}
[XmlElementAttribute(Order = 5)]
public string Other { get; set; }
[XmlElementAttribute(Order = 6, ElementName = "SalesOrderLineMod")]
public List<LineMod> SalesOrderLineMod = new List<LineMod>();
[XmlElementAttribute(Order = 7, ElementName = "SalesOrderLineGroupMod")]
public List<LineMod> SalesOrderLineGroupMod = new List<LineMod>();
}
You originally indicated you would like to serialize a series of elements inside an XML document like so:
<SalesOrderLineRet>
</SalesOrderLineRet>
<SalesOrderLineGroupRet>
</SalesOrderLineGroupRet>
<SalesOrderLineRet>
</SalesOrderLineRet>
You can if the types that correspond to SalesOrderLineRet and SalesOrderLineGroupRet have some common base type T, and they are stored in a List<T>. For instance, the following class definitions:
public abstract class SalesOrderLineRetBase
{
}
public class SalesOrderLineRet : SalesOrderLineRetBase
{
}
public class SalesOrderLineGroupRet : SalesOrderLineRetBase
{
}
public class RootObject
{
[XmlElement(typeof(SalesOrderLineRetBase))]
[XmlElement(typeof(SalesOrderLineRet))]
[XmlElement(typeof(SalesOrderLineGroupRet))]
public List<SalesOrderLineRetBase> SalesOrders { get; set; }
}
Will, when serialized, produce the following XML:
<RootObject>
<SalesOrderLineRet />
<SalesOrderLineGroupRet />
</RootObject>
Using [XmlElement(typeof(T))] tells XmlSerializer that the list should be serialized without an outer container element, and that items of type T can be expected to be found in the list. You must apply [XmlElement(typeof(T))] once for each type T that will be stored in the list.
(You can use List<object> if the types in the list have no other more derived base type, however I don't recommend that. I would instead recommending grouping the possible types of list entry under a specific base type.)
If you would prefer your list to be serialized with an outer container element, you can use [XmlArray] and [XmlArrayItem(typeof(T))]:
public abstract class SalesOrderLineRetBase
{
}
public class SalesOrderLineRet : SalesOrderLineRetBase
{
}
public class SalesOrderLineGroupRet : SalesOrderLineRetBase
{
}
public class RootObject
{
[XmlArray("SalesOrders")]
[XmlArrayItem(typeof(SalesOrderLineRetBase))]
[XmlArrayItem(typeof(SalesOrderLineRet))]
[XmlArrayItem(typeof(SalesOrderLineGroupRet))]
public List<SalesOrderLineRetBase> SalesOrders { get; set; }
}
Which produces the following XML:
<RootObject>
<SalesOrders>
<SalesOrderLineRet />
<SalesOrderLineGroupRet />
</SalesOrders>
</RootObject>
You must apply [XmlArrayItem(typeof(T))] for each type T that will be stored in the list.
(Since you don't include the relevant classes and XML in your question, I'm not sure which one you might want.)
There have been a number of questions about serializing and deserializing arrays using DataContractJsonSerializer (including one from me: How can I serialise a string array to JSON using DataContractJsonSerializer?) but none seem to answer the current problem that I'm having.
I am converting an XML string to a JSON string by deserializing the XML to a DataContract object and then serializing that object to JSON, using DataContractJsonSerializer. My approach is the same as I have used on a number of other objects, all of which are serializing to JSON perfectly, but I have an object in which an array property is always rendered as null after serialization.
The classes are defined as follows:-
[DataContract]
public class Order
{
[DataMember(Name = "consignments")]
[XmlElement("consignments")]
public Consignment[] Consignments { get; set; }
}
[DataContract]
public class Consignment
{
[DataMember(Name = "conh_id")]
[XmlElement("conh_id")]
public string ConsignmentHeaderId { get; set; }
[DataMember(Name = "conh_status")]
[XmlElement("conh_status")]
public string ConsignmentHeaderStatus { get; set; }
[DataMember(Name = "consignmententries")]
[XmlElement("consignmententries")]
public ConsignmentEntry[] ConsignmentEntries { get; set; }
}
The XML I'm using looks like this:-
<order>
<consignments>
<consignment>
<conh_id>A19708176</conh_id>
<conh_status>ACCEPTED</conh_status>
<consignmententries>
<consignmententry>
<conl_lineNbr>10000</conl_lineNbr>
<conl_sku>SEC01XXZBUXXX</conl_sku>
<conl_original_qty>1</conl_original_qty>
</consignmententry>
</consignmententries>
</consignment>
</consignments>
</order>
The deserializing and serializing is done in the following methods:-
private object DeserialiseXml(string xml)
{
var serialiser = new XmlSerializer(typeof(Order));
var stringReader = new StringReader(xml);
var result = serialiser.Deserialize(stringReader);
return result;
}
private string SerialiseJson(object serialisable)
{
using (MemoryStream stream = new MemoryStream())
{
var serialiser = new DataContractJsonSerializer(serialisable.GetType());
serialiser.WriteObject(stream, serialisable);
var json = Encoding.UTF8.GetString(stream.ToArray());
return json;
}
}
When I test it, the Consignments property is always null in the resulting JSON.
"order": {
"consignments": [
{
"conh_id": null,
"conh_status": null,
"consignmententries": null
}
]
}
Debugging shows that this property is null in the object created after the deserialization step so the problem is in the XML deserialization rather than the JSON serialization.
What do I need to change on my object model to get the array converted properly?
Your problem is happening when you deserialize from XML rather than when you serialize to JSON. In your XML, the collections have been serialized with two levels: an outer container element and an element for each item:
<consignments>
<consignment>
<!-- Consignment data -->
</consignment>
</consignments>
And
<consignmententries>
<consignmententry>
<!-- Entry data -->
</consignmententry>
</consignmententries>
(For comparison, in the linked question the Labels XML collection has a single level). Thus you need to use [XmlArray(string name)] and [XmlArrayItem(string itemName)] to specify the outer and inner element names:
[DataContract]
[XmlRoot("order")]
public class Order
{
[DataMember(Name = "consignments")]
[XmlArray("consignments")]
[XmlArrayItem("consignment")]
public Consignment[] Consignments { get; set; }
}
[DataContract]
public class Consignment
{
[DataMember(Name = "conh_id")]
[XmlElement("conh_id")]
public string ConsignmentHeaderId { get; set; }
[DataMember(Name = "conh_status")]
[XmlElement("conh_status")]
public string ConsignmentHeaderStatus { get; set; }
[DataMember(Name = "consignmententries")]
[XmlArray("consignmententries")]
[XmlArrayItem("consignmententry")]
public ConsignmentEntry[] ConsignmentEntries { get; set; }
}
Conversely, adding the attribute [XmlElement] to a collection tells XmlSerializer that the collection should be serialized without the outer container element.
You also need to add [XmlRoot("order")] to Order to specify the root element name.
Now your XML will deserialize successfully.
I am writing a WCF service that generates various XML and JSON formats for multiple clients. The code below generates a SerializationException: 'TPH_PriceListJsonItems' is a collection type and cannot be serialized when assigned to an interface type that does not implement IEnumerable ('TPH_IPriceListItems'). The XML part is working fine, but not JSON. I do not understand the error, my interface is implementing IEnumerable to represent a class wrapping a simple List<> so I can use the CollectionDataContract.
public class ReproduceDataContractIssue
{
public static void Main(String[] args)
{
// Create test object - vacation products lowest prices grid
TPH_IPriceList priceList = new TPH_PriceListJson();
priceList.ListItems.Add(new TPH_PriceListJsonItem() { DestCityName = "Cancun", StayDuration = 7, LowestPrice = 1111 });
priceList.ListItems.Add(new TPH_PriceListJsonItem() { DestCityName = "Jamaica", StayDuration = 14, LowestPrice = 2222 });
// Serialize into XML string
DataContractSerializer serializer = new DataContractSerializer(priceList.GetType());
MemoryStream memStream = new MemoryStream();
serializer.WriteObject(memStream, priceList);
memStream.Seek(0, SeekOrigin.Begin);
string xmlOutput;
using (var streamReader = new StreamReader(memStream))
xmlOutput = streamReader.ReadToEnd();
// Serialize into JSON string
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(priceList.GetType());
jsonSerializer.WriteObject(memStream = new MemoryStream(), priceList);
memStream.Seek(0, SeekOrigin.Begin);
string jsonOutput;
using (var streamReader = new StreamReader(memStream))
jsonOutput = streamReader.ReadToEnd();
}
}
public interface TPH_IPriceList
{
TPH_IPriceListItems ListItems { get; set; }
}
public interface TPH_IPriceListItems : IEnumerable<TPH_IPriceListItem>, IEnumerable, IList<TPH_IPriceListItem>
{
}
public interface TPH_IPriceListItem
{
string DestCityName { get; set; }
int StayDuration { get; set; }
int LowestPrice { get; set; }
}
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[DataMember]
public TPH_IPriceListItems ListItems { get; set; }
public TPH_PriceListJson()
{
ListItems = new TPH_PriceListJsonItems();
}
}
[DataContract]
public class TPH_PriceListJsonItem : TPH_IPriceListItem
{
[DataMember(Order = 1)]
public string DestCityName { get; set; }
[DataMember(Order = 2)]
public int StayDuration { get; set; }
[DataMember(Order = 3)]
public int LowestPrice { get; set; }
public TPH_PriceListJsonItem()
{
}
}
[CollectionDataContract(Name = "ListItems", ItemName = "ListItem")]
[KnownType(typeof(TPH_PriceListJsonItem))]
public class TPH_PriceListJsonItems : List<TPH_IPriceListItem>, TPH_IPriceListItems, IEnumerable<TPH_IPriceListItem>, IEnumerable
{
public TPH_PriceListJsonItems(int capacity)
: base(capacity)
{
}
public TPH_PriceListJsonItems()
: base()
{
}
}
}
The inconsistency arises from a difference in how JSON and XML represent collections. For XML, the data contract serializers convert a collection to a nested set of elements -- an outer collection wrapper, and an inner element for each item in the collection. For JSON, the serializers convert a collection to an array containing objects. This seems reasonable, but there's a difference between the two: the XML outer element can have its own XML attributes, but JSON arrays cannot have their own properties -- there's simply no place for them in the standard.
This becomes an issue in dealing with type hints. Type hints are properties added to the serialized data to indicate, in the event of serializing an interface or base class of a class hierarchy, what concrete class was actually serialized. They are required to enable deserialization of the object without data loss. In XML, they appear as an i:type attribute:
<PriceList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Question32569055.V1">
<ListItems i:type="ListItems"> <!-- Notice the type hint here. -->
<ListItem i:type="TPH_PriceListJsonItem"> <!-- Notice the type hint here also. -->
<DestCityName>Cancun</DestCityName>
<StayDuration>7</StayDuration>
<LowestPrice>1111</LowestPrice>
</ListItem>
</ListItems>
</PriceList>
As you can see from your own example, type hints can be added for both collection and non-collection classes.
In JSON objects, they appear as an added property named "__type":
{
"__type": "TPH_PriceListJsonItem:#Question32569055.V3",
"DestCityName": "Cancun",
"StayDuration": 7,
"LowestPrice": 1111
}
But, as mentioned before, JSON arrays cannot have properties. So, what does DataContractJsonSerializer do for polymorphic collection types? Well, other than for a few standard collection interfaces which, as Fabian notes, are mapped to collection classes using hardcoded logic, it throws a cryptic exception to indicate that subsequent deserialization would be impossible. (For comparison, Json.NET introduces an extra container object to hold collection type information. See TypeNameHandling setting.)
The solution to this inconsistency is to serialize the collection explicitly as a concrete collection (TPH_PriceListJsonItems in your case) rather than as an interface:
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[IgnoreDataMember]
public TPH_IPriceListItems ListItems
{
get
{
return ListItemList;
}
set
{
var list = value as TPH_PriceListJsonItems;
if (list == null)
{
list = new TPH_PriceListJsonItems();
if (value != null)
list.AddRange(value);
}
ListItemList = list;
}
}
[DataMember(Name = "ListItems")]
TPH_PriceListJsonItems ListItemList { get; set; }
public TPH_PriceListJson()
{
ListItemList = new TPH_PriceListJsonItems();
}
}
This eliminates the need for the type hint on the collection element while retaining it for collection members. It generates the following XML:
<PriceList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Question32569055.V3">
<ListItems> <!-- No type hint here any more. -->
<ListItem i:type="TPH_PriceListJsonItem"> <!-- But the type hint is still here. -->
<DestCityName>Cancun</DestCityName>
<StayDuration>7</StayDuration>
<LowestPrice>1111</LowestPrice>
</ListItem>
</ListItems>
</PriceList>
And produces the following JSON:
{
"ListItems": [
{
"__type": "TPH_PriceListJsonItem:#Question32569055.V3",
"DestCityName": "Cancun",
"StayDuration": 7,
"LowestPrice": 1111
},
]
}
This design allows the class TPH_IPriceListItems to control exactly what type of collection is used internally rather than leaving it up to users of the class, and thus seems like a preferable design overall.
Looks like it is a similar problem to this one. The List of supported interfaces in DataContractJsonSerializer is hardcoded. So you can't add your own List Wrapper interface.
Why don't you just drop TPH_IPriceListItems like in the following code ? It is simpler and should also do what you want:
public interface TPH_IPriceList
{
IList<TPH_IPriceListItem> ListItems { get; set; }
}
public interface TPH_IPriceListItem
{
string DestCityName { get; set; }
int StayDuration { get; set; }
int LowestPrice { get; set; }
}
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[DataMember]
public IList<TPH_IPriceListItem> ListItems { get; set; }
public TPH_PriceListJson()
{
ListItems = new TPH_PriceListJsonItems();
}
}
[DataContract]
public class TPH_PriceListJsonItem : TPH_IPriceListItem
{
[DataMember(Order = 1)]
public string DestCityName { get; set; }
[DataMember(Order = 2)]
public int StayDuration { get; set; }
[DataMember(Order = 3)]
public int LowestPrice { get; set; }
}
[CollectionDataContract(Name = "ListItems", ItemName = "ListItem")]
[KnownType(typeof(TPH_PriceListJsonItem))]
public class TPH_PriceListJsonItems : List<TPH_IPriceListItem>
{
}