0

I have an XML and when converting to JSON, all the values became string as below:

XML:
<root><deviceToEgressLocationDistance>600</deviceToEgressLocationDistance></root>
JSON:
{ "deviceToEgressLocationDistance": "600" }

while it should be

JSON:
{ "deviceToEgressLocationDistance": 600 }

below the code I am using but it converts everything to strings

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
string jsonContent = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);

I have checked the solution in Serialize Xml to Json using type attribute in c#

but I cannot manually parse every value as the xml file properties are changing every time so the next time it could be

XML:
<root><Location1>500.88</Location1><Location2>650</Location2></root>

The xml could have any structure including nesting properties.

Any ideas?

Update: After converting the XML to JSON, this JSON file is going to be the source to another system and if the JSON file has the wrong types like treating numbers as string or even DateTime as string, the subsystem fail to process the input source. So, I need to preserve the types in XML when converting to JSON

Jimmy
  • 17
  • 5
  • 4
    Deserialize this into an object model which has `int deviceToEgressLocationDistance;` and the re-serialize as JSON – Charlieface Aug 11 '22 at 20:33
  • Does this answer your question? [How to convert JSON to XML or XML to JSON?](https://stackoverflow.com/questions/814001/how-to-convert-json-to-xml-or-xml-to-json) – Heretic Monkey Aug 11 '22 at 23:00
  • No, They are using the exact code in my question. it does not solve the type issue – Jimmy Aug 12 '22 at 00:18
  • You have to do it like in this [post](https://stackoverflow.com/questions/50911325/convert-xml-string-to-c-sharp-object). First, convert XML to Object. You need to define class for this object. Later, convert object to JSON. – ahmet gül Aug 12 '22 at 08:15
  • @ahmetgül as I mentioned in my question, I do not have a schema. the file structure is changing so I cannot really convert to an object since I won't have a class to convert to. – Jimmy Aug 12 '22 at 16:05
  • Hey, in that case you can create a class which contains all kind of attribute, In your testing, when you see a new property, add it to your class. I am pretty sure that those who prepare the XML send with specific schema. – ahmet gül Aug 15 '22 at 08:41

0 Answers0