有没有办法阻止Newtonsoft的JsonConvert.SerializeObject
方法用字符串替换整数?下面的示例代码:
XmlDocument doc = new XmlDocument();
string xml = @"<data><someProperty>12345</someProperty></data>";
doc.LoadXml(xml);
string json = JsonConvert.SerializeObject(doc);
当前输出为
{"data":{"someProperty":"12345"}}
而我想要的输出是
{"data":{"someProperty":12345}}
如果您重写JsonTextWriter
,您应该能够截取每个字符串值,尝试解析它,并以不同的方式写出它。
public class XmlIntWriter : JsonTextWriter
{
public XmlIntWriter(TextWriter textWriter) : base(textWriter)
{
}
public override void WriteValue(string value)
{
if (int.TryParse(value, out var i))
this.WriteValue(i);
else
base.WriteValue(value);
}
}
将您的自定义编写器与Newtonsoft xml转换器一起使用有点麻烦,但应该看起来像;
public static void Serialise(XDocument doc, TextWriter writer)
{
var converter = new XmlNodeConverter ();
var settings = new JsonSerializerSettings
{
Converters = new JsonConverter[] { converter }
};
var serializer = JsonSerializer.Create(settings);
using var xmlWriter = new XmlIntWriter(writer);
serializer.Serialize(xmlWriter, doc);
}
(我还没有测试过这些(