I have a field containing raw HTML published via JSON that was recently converted from a string to an IHtmlString. When that change happened, the field went from being a JSON string to being an empty object and a bunch of things consuming that JSON started blowing up.
// When it was a string...
{
someField: "some <span>html</span> string"
}
// When it became an IHtmlString...
{
someField: { }
}
Ignoring any arguments against raw HTML in JSON since it is moot for this project, how do I get the expected string in my JSON serialization?
Background
Both Json.NET and the default .NET JavaScriptSerializer will treat instances of
IHtmlStringas an object with no properties and serialize it into an empty object. Why? Because it is an interface with only one method and methods don’t serialize to JSON.Solution
For Json.NET, you will need to create a custom
JsonConverterthat will consume anIHtmlStringand output the raw string.With that in place, send an instance of your new
IHtmlStringConverterto Json.NET’sSerializeObjectcall.Sample Code
For an example MVC project where a controller demos this, head over to this question’s GitHub repository.