简体   繁体   中英

Serialize Xml to Json using type attribute in c#

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM