简体   繁体   中英

How to stop JsonConvert.SerializeObject from changing ints to strings when converting XML to JSON

Is there a way to prevent Newtonsoft's JsonConvert.SerializeObject method to replace integers with strings? Sample code below:

XmlDocument doc = new XmlDocument();
string xml = @"<data><someProperty>12345</someProperty></data>";
doc.LoadXml(xml);
string json = JsonConvert.SerializeObject(doc);

The current output is

{"data":{"someProperty":"12345"}}

whereas the output I want is

{"data":{"someProperty":12345}}

If you override JsonTextWriter you should be able to intercept every string value, try to parse it, and write it out differently.

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

Using your custom writer with the Newtonsoft xml converter is a little fiddly, but should look something like;

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

(I haven't tested any of this)

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