The JSON.NET framework can convert XML to JSON, but it uses the @ sign in the JSON as the attribute. I would rather remove this before sending it to the view. What would b
It took me quite a while to find the right answer, so I thought I'd share:
var xDocument = XDocument.Parse("c ");
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder)), xDocument);
var serialized = builder.ToString();
public class CustomJsonWriter : JsonTextWriter
{
public CustomJsonWriter(TextWriter writer): base(writer){}
public override void WritePropertyName(string name)
{
if (name.StartsWith("@") || name.StartsWith("#"))
{
base.WritePropertyName(name.Substring(1));
}
else
{
base.WritePropertyName(name);
}
}
}
Output:
{"xml":{"a":{"attr":"b","text":"c"}}}