JSON.NET is not a tool for XML serialization. It's serialization of XML nodes is meant to provide one-to-one correspondence between XML and JSON. As attributes in XML can be only of type string, type information is not preserved during the serialization. It will be useless when deserializing back to JSON.
If you need to convert XML to JSON, I suggest using a DTO class which supports both XML and JSON serialization.
[XmlRoot ("Object"), JsonObject]
public class Root
{
[XmlElement, JsonProperty]
public int Id { get; set; }
[XmlElement, JsonProperty]
public string Title { get; set; }
[XmlElement, JsonProperty]
public bool Visible { get; set; }
}
Deserialize from XML and then serialize to JSON:
public class Program
{
private const string xml = @"
<Object>
<Id>12</Id>
<Title>mytitle</Title>
<Visible>false</Visible>
</Object>";
private static void Main ()
{
var serializer = new XmlSerializer(typeof(Root));
var root = (Root)serializer.Deserialize(new StringReader(xml));
Console.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
Console.ReadKey();
}
}
Output:
{
"Id": 12,
"Title": "mytitle",
"Visible": false
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…