I am trying to convert an XML to JSON without changing the datatypes but it is always returning the string value. I have tried different ways to convert with proper data types.
Below is my source XML and expected JSON
<Employee >
<Name>John</Name>
<Age>18</Age>
<IsContractor>true</IsContractor>
<Salary>5555.66</Salary>
</Employee>
Expected Result:
"Employee": {
"Name": "John",
"Age": 18,
"IsContractor": true,
"Salary": 5555.66
}
I have tried different ways but no luck
string xml = @"<Employee>
<Name>John</Name>
<Age json:Type='Integer'>18</Age>
<IsContractor json:Type='Boolean'>true</IsContractor>
<Salary json:Type='Decimal'>5555.66</Salary>
</Employee>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var result = JsonConvert.SerializeXmlNode(doc);
Also, I tried adding a datatype like this
var xml = @"<Employee xmlns:m=""urn:informatica:ae:xquery:json2xml:meta-data"">
<Name>John</Name>
<Age m:type=""xs:double"">18</Age>
<IsContractor m:type=""xs:boolean"">true</IsContractor>
</Employee>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var result1 = JsonConvert.SerializeXmlNode(doc);
But both ways all the values are converted to a string.
2
Answers
You could use a workaround that utilizes Newtonsoft.Json to convert XML to JSON and then parse the JSON again to convert the string values to their appropriate data types.
This code works for me. If you have nested objects for example you just need to change an iteration algorithm
output