Having empty Dictionary<int, string>
how to fill it with keys and values from XML like
<items>
<item id='int_goes_here' value='string_goes_here'/>
</items>
and serialize it back into XML not using XElement?
Having empty Dictionary<int, string>
how to fill it with keys and values from XML like
<items>
<item id='int_goes_here' value='string_goes_here'/>
</items>
and serialize it back into XML not using XElement?
Dictionaries are not Serializable in C# by default, I don't know why, but it seems to have been a design choice.
Right now, I'd recommend using Json.NET to convert it to JSON and from there into a dictionary (and vice versa). Unless you really need the XML, I'd recommend using JSON completely.
I have a struct
KeyValuePairSerializable
:Then, the XML serialization of a
Dictionary
property is by:Just the property must be the array, not the List.
You can use ExtendedXmlSerializer. If you have a class:
and create instance of this class:
You can serialize this object using ExtendedXmlSerializer:
Output xml will look like:
You can install ExtendedXmlSerializer from nuget or run the following command:
Based on L.B.'s answer.
Usage:
Generic class:
With the help of a temporary
item
classSample Dictionary:
.
Serialization
Deserialization
------------------------------------------------------------------------------
Here is how it can be done using XElement, if you change your mind.
Serialization
Deserialization
Paul Welter's ASP.NET blog has a dictionary that is serializeable. But it does not use attributes. I will explain why below the code.
First, there is one gotcha with this code. Say you read a dictionary from another source that has this:
This will throw a exception on de-seariazation because you can only have one key for a dictionary.
The reason you MUST use a XElement in a seriazed dictionary is dictionary is not defined as
Dictionary<String,String>
, a dictionary isDictionary<TKey,TValue>
.To see the problem, ask your self: Lets say we have a
TValue
that serializes in to something that uses Elements it describes itself as XML (lets say a dictionary of dictionariesDictionary<int,Dictionary<int,string>>
(not that uncommon of a pattern, it's a lookup table)), how would your Attribute only version represent a dictionary entirely inside a attribute?