Newtonsoft.Json.JsonConvert
类中的 SerializeXmlNode
函数在序列化过程中总是将 XML 的最后一个子节点的值输出为字符串类型,有时有时您可能需要将它们序列化为整数或布尔值.
The SerializeXmlNode
function from Newtonsoft.Json.JsonConvert
class always outputs the value of the last child nodes of a XML as a string type in the serialization process, when sometimes you might need them to be serialized as an Integer or a Boolean.
示例代码:
<Object>
<ID>12</ID>
<Title>mytitle</Title>
<Visible>false</Visible>
</Object>
输出:
{ "ID" : "12",
"Title" : "mytitle",
"Visible" : "false"
}
期望的输出:
{ "ID" : 12,
"Title" : "mytitle",
"Visible" : false
}
有没有办法强制将 XML 节点序列化为整数或布尔值?
Is there a way to force a XML node to be serialized as a Integer or a Boolean?
谢谢.
注意:当 XML 已经序列化为 JSON 字符串时,请避免发布解决方法,因为这些解决方法是我们愿意避免的.
Note: Please avoid posting workarounds when the XML is already serialized to a JSON string, as those workarounds are the ones that we are willing to avoid.
当前的 JSON.NET 构建不提供请求的功能,所以我修改了源代码以提供此功能:
The current JSON.NET build doesn't provide the requested feature, so I modified the source code to provide this functionality:
https://github.com/lukegothic/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs
此修改为 XmlNodeConverter 提供了一种从 XML 节点读取可选属性的方法,该属性称为类型",该属性包含所需的节点值序列化.默认情况下,转换器将结果 JSON 字符串中的所有值序列化为字符串,但现在您可以添加一个属性来指定所需的 DataType 输出.允许的类型为 Integer、Float、Boolean 和 Date.
This modification provides the XmlNodeConverter a way to read an optional attribute from XML nodes called "Type" that holds the desired serialization of a node value. By default, the converter serializes all values as string in the result JSON string, but now you can add an attribute that specifies the desired DataType output. The allowed types are Integer, Float, Boolean and Date.
例如,如果你有这个源 XML:
For example, if you have this source XML:
<Object>
<ID json:Type='Integer'>12</ID>
<Title>mytitle</Title>
<Visible json:Type='Boolean'>false</Visible>
<Price json:Type='Float'>1.55</Price>
<ExpirationDate json:Type='Date'>2013-12-31</ExpirationDate>
</Object>
会被序列化为:
{
"ID":12,
"Title":"mytitle",
"Visible":false,
"Price":1.55,
"ExpirationDate":"2013-12-31T00:00:00"
}
这篇关于强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!