JSON.NET - 我可以提示解析XML中的类型吗?

时间:2012-05-09 16:22:37

标签: xml parsing types json.net

当我使用JsonConvert.SerializeXNode或JsonConvert.SerializeXmlNode解析XML时,以下代码

XElement person = XElement.Parse(@"
  <person>
    <name>Palle</name>
    <member>true</member>
  </person>");

string json = JsonConvert.SerializeXNode(person);

给我这个json结果:

{"person":{"name":"Palle","member":"true"}}

这里的成员被键入为字符串,我希望将其键入为bool。我可以在XML中添加类型提示(例如<member type="xsd:boolean">true</member>)并让解析器接受吗?

我希望得到这个结果:

{"person":{"name":"Palle","member":true}}

1 个答案:

答案 0 :(得分:0)

也许是这样的:

[TestFixture]
public class Class1
{
    [Test]
    public void DateTimeTest()
    {
        string xml = @"<person><name>Palle</name><member>true</member></person>";
        person person = xml.Deserialize<person>();
        var serializeXNode = JsonConvert.SerializeObject(person);
    }
}

public class person
{
    public string name { get; set; }
    public bool member { get; set; }
}

public static class Extension
{
    public static T Deserialize<T>(this string xml)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        using (var stringReader = new StringReader(xml))
        {
            using (var xmlReader = XmlReader.Create(stringReader))
            {
                return (T) xmlSerializer.Deserialize(xmlReader);
            }
        }
    }
}