问题
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.
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");
where ele
comes from XmlElement ele = node as XmlElement;
The result always ends up with something like this:
"id": {
"@Type": "Integer",
"#text": "759263947"
},
but what I need is
"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");
which is working just fine.
Laura
回答1:
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");
Or, for a double value:
ele.SetAttribute("Type", "http://james.newtonking.com/projects/json", "Float");
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);
来源:https://stackoverflow.com/questions/29909328/convert-a-json-value-to-integer-with-newtonsoft