C# Question

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

The

SerializeXmlNode
function from
Newtonsoft.Json.JsonConvert
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:

<Object>
<ID>12</ID>
<Title>mytitle</Title>
<Visible>false</Visible>
</Object>


Output:

{ "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

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

https://github.com/lukegothic/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs

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:

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

It will be serialized as:

{
    "ID":12,
    "Title":"mytitle",
    "Visible":false,
    "Price":1.55,
    "ExpirationDate":"2013-12-31T00:00:00"
}
Comments