【发布时间】:2014-03-31 19:49:17
【问题描述】:
我正在使用 SerializeXmlNode 从 XML 转换为 JSON。看起来预期的行为是将所有 XML 值转换为字符串,但我想在适当的地方发出真正的数值。
// Input: <Type>1</Type>
string json = JsonConvert.SerializeXmlNode(node, Newtonsoft.Json.Formatting.Indented, true);
// Output: "Type": "1"
// Desired: "Type": 1
我是否需要编写一个自定义转换器来执行此操作,或者是否有办法通过委托在适当的点挂钩到序列化过程?或者,我必须编写自己的自定义 JsonConverter 类来管理转换吗?
正则表达式破解
考虑到正确解决方案的复杂性,这里有另一个(我并不完全为它感到自豪,但它确实有效......)。
// Convert to JSON, and remove quotes around numbers
string json = JsonConvert.SerializeXmlNode(node, Newtonsoft.Json.Formatting.Indented, true);
// HACK to force integers as numbers, not strings.
Regex rgx = new Regex("\"(\\d+)\"");
json = rgx.Replace(json, "$1");
【问题讨论】: