且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Newtonsoft将Json值转换为Integer

更新时间:2023-01-17 19:45:31

如果您正在使用 https://github.com/lukegothic/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters /XmlNodeConverter.cs ,看来您需要这样做:

If you are using the variant version of XmlNodeConverter described in this answer and available here: https://github.com/lukegothic/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs, it looks like you would need to do:

ele.SetAttribute("Type", "http://james.newtonking.com/projects/json", "Integer");

或者,对于双精度值:

ele.SetAttribute("Type", "http://james.newtonking.com/projects/json", "Float");

或者,您可以直接使用Linq-to-JSON手动将转换字符串值修改为数字值,例如:

Alternatively, you could use Linq-to-JSON out-of-the-box to manually modify convert string values to numeric values, for instance:

        string xml = @"<fulfillment xmlns:json=""http://james.newtonking.com/projects/json""><tracking_number>937467375966</tracking_number><tracking_url>google.com/search?q=937467375966</tracking_url>; <line_items json:Array=""true""><id>759263947</id><quantity>1.00000</quantity></line_items></fulfillment>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var obj = JObject.Parse(JsonConvert.SerializeXmlNode(doc));
        foreach (var value in obj.Descendants().OfType<JValue>().Where(v => v.Type == JTokenType.String))
        {
            long lVal;
            if (long.TryParse((string)value, out lVal))
            {
                value.Value = lVal;
                continue;
            }
            double dVal;
            if (double.TryParse((string)value, out dVal))
            {
                value.Value = dVal;
                continue;
            }
            decimal dcVal;
            if (decimal.TryParse((string)value, out dcVal))
            {
                value.Value = dcVal;
                continue;
            }
        }
        var json = obj.ToString();
        Debug.WriteLine(json);