如何使用Json.NET将IHtmlString序列化为JSON? [英] How do I serialize IHtmlString to JSON with Json.NET?

查看:51
本文介绍了如何使用Json.NET将IHtmlString序列化为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含通过JSON发布的原始HTML的字段,该字段最近已从字符串转换为IHtmlString.当发生这种变化时,该字段就从一个JSON字符串变成了一个空对象,并且消耗了JSON的许多东西开始爆炸.

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: { }
}

由于该项目尚无定论,因此忽略JSON中针对原始HTML的任何参数,如何在JSON序列化中获得预期的字符串?

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?

推荐答案

背景

Json.NET和默认的.NET JavaScriptSerializer都将IHtmlString的实例视为没有属性的对象,并将其序列化为空对象.为什么?因为它是一个只有一种方法的接口,而且方法不会序列化为JSON.

Background

Both Json.NET and the default .NET JavaScriptSerializer will treat instances of IHtmlString as 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.

public interface IHtmlString {
    string ToHtmlString();
}

解决方案

对于Json.NET,您将需要创建一个自定义JsonConverter,它将使用IHtmlString并输出原始字符串.

Solution

For Json.NET, you will need to create a custom JsonConverter that will consume an IHtmlString and output the raw 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) {
        // warning, not thoroughly tested
        var html = reader.Value as string;
        return html == null ? null : System.Web.Mvc.MvcHtmlString.Create(html);
    }
}

在适当的位置上,将新的IHtmlStringConverter的实例发送到Json.NET的SerializeObject调用.

With that in place, send an instance of your new IHtmlStringConverter to Json.NET's SerializeObject call.

string json = JsonConvert.SerializeObject(objectWithAnIHtmlString, new[] { new IHtmlStringConverter() });

示例代码

对于一个控制器进行演示的示例MVC项目,请转到此问题的GitHub存储库.

这篇关于如何使用Json.NET将IHtmlString序列化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆