本文介绍了使用Newtonsoft将Json值转换为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将属性添加到xml中,以指定在使用JsonConvert.SerializeXmlNode时此节点应返回Integer值.

I am using the following code to add an attribute to my xml to designate that this node should return an Integer value when using JsonConvert.SerializeXmlNode.

我已将Newtonsoft的更新合并到我引用的dll中.

I have incorporated the update from Newtonsoft into my referenced dll.

我正在使用以下代码添加属性:

I am using the following code to add the attribute:

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

其中ele来自XmlElement ele = node as XmlElement;

结果总是以如下形式结束:

The result always ends up with something like this:

 "id": {
        "@Type": "Integer",
        "#text": "759263947"
      },

但是我需要的是

"id": 759263947

请注意,我使用完全相同的语法来标识一个数组:

Please note that I use the exact same syntax to identify an an Array:

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

效果很好.

劳拉

推荐答案

如果您正在使用,并在此处提供: 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);

这篇关于使用Newtonsoft将Json值转换为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:04