C# Question

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean


function from
class always outputs the value of the last child nodes of a XML as a string type in the serialization process, when sometimes you might need them to be serialized as an Integer or a Boolean.

Sample code:



{ "ID" : "12",
"Title" : "mytitle",
"Visible" : "false"

Desired output:

{ "ID" : 12,
"Title" : "mytitle",
"Visible" : false

Is there a way to force a XML node to be serialized as a Integer or a Boolean?

Thank you.

Note: Please avoid posting workarounds when the XML is already serialized to a JSON string, as those workarounds are the ones that we are willing to avoid.

Answer Source

The current JSON.NET build doesn't provide the requested feature, so I modified the source code to provide this functionality:


This modification provides the XmlNodeConverter a way to read an optional attribute from XML nodes called "Type" that holds the desired serialization of a node value. By default, the converter serializes all values as string in the result JSON string, but now you can add an attribute that specifies the desired DataType output. The allowed types are Integer, Float, Boolean and Date.

For example, if you have this source XML:

  <ID json:Type='Integer'>12</ID>
  <Visible json:Type='Boolean'>false</Visible>
  <Price json:Type='Float'>1.55</Price>
  <ExpirationDate json:Type='Date'>2013-12-31</ExpirationDate>

It will be serialized as:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download