Background
Both Json.NET and standard JavaScriptSerializer, by default, process IHtmlString
instances as an object with no properties and serialize it to an empty object. What for? Since this is an interface with only one method, and the methods are not serialized in JSON.
public interface IHtmlString { string ToHtmlString(); }
Decision
For Json.NET, you need to create a custom JsonConverter
that will consume IHtmlString
and output the original string.
public class IHtmlStringConverter : Newtonsoft.Json.JsonConverter { public override bool CanConvert(Type objectType) { return typeof(IHtmlString).IsAssignableFrom(objectType); } public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { IHtmlString source = value as IHtmlString; if (source == null) { return; } writer.WriteValue(source.ToString()); } public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) {
In doing so, send an instance of your new IHtmlStringConverter
call to Json.NET SerializeObject
.
string json = JsonConvert.SerializeObject(objectWithAnIHtmlString, new[] { new IHtmlStringConverter() });
Code example
For an example MVC project where the controller demonstrates this, go to this question on the GitHub repository .
source share