JSON.NET and Replacing @ Sign in XML to JSON converstion

后端 未结 10 1994
野的像风
野的像风 2020-12-11 01:32

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

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 01:49

    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"}}}
    

提交回复
热议问题