在 C# 中使用类型属性将 Xml 序列化为 Json

Serialize Xml to Json using type attribute in c#

我想在 json 中序列化我的 xml 并保持数字类型。

下面我的XML:

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

这是我的预期结果:

{
"root": 42
}

我正在尝试使用 Newtonsoft 库,使用 JsonConvert.SerializeXmlNode 方法但似乎不起作用:

我的代码:

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;

结果:

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

你能帮帮我吗?

您的 XML 与您预期的 JSON 没有任何相关性。这完全是您可能喜欢的手动转换(我假设您的意思是 42,否则请解释获得 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);
}