0

I would like to serialize my xml in a json keeping the number type.

Below my XML:

<root type="number">42</root>

Here my expected result:

{
"root": 42
}

I'm trying to use the Newtonsoft Library, using JsonConvert.SerializeXmlNode method but seems that doesn't work:

MY CODE:

XmlDocument dox1 = new XmlDocument();
string xx = "<root type=\"number\">42</root>";
dox1.LoadXml(xx);

string JsonContent = Newtonsoft.Json.JsonConvert.SerializeXmlNode(dox1, Newtonsoft.Json.Formatting.Indented, true);
//JsonResult json = Json(JsonContent);
return JsonContent;

THE RESULT:

{
"@type": "number",
"#text": "42"
}

Can you help me?

Luke
  • 517
  • 10
  • 29
  • In XML there is only strings (XSD changes that, but I've no idea if JSON.NET's XML supports XSD). For anything other than simple cases you really need to write code. – Richard Oct 12 '18 at 12:39

1 Answers1

1

Your XML doesn't have any relevance to your expected JSON. It is totally a manual conversion which you might do like (I assume you meant 42, else explain the logic getting 4):

void Main()
{
    string xx = "<root type=\"number\">42</root>";
    var value = new { orderType = (int)XElement.Parse(xx)};
    var json = JsonConvert.SerializeObject(value);
    Console.WriteLine(json);
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
  • Anyway thank you, you open my mind :) i'll use your way to personalize dynamically my parsing watching at the type format in my xml – Luke Oct 12 '18 at 13:33