0

我的应用程序需要将依赖注入的广泛使用与 JSON 作为公共 API 的使用结合起来。这显然导致需要自定义 JavaScriptConverter。

现在,我的 JavaScriptConverter 的 Deserialize 方法如下所示:

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
    var result = IocHelper.GetForType(type);
    return result;
}

这会交还适当的课程。不幸的是,它无法使用适用的值填充类成员。我缺少的是一种告诉序列化器的方法,“这是你要求的类型。现在填写。”

4

1 回答 1

1

我使用的解决方案是从 JavaScriptSerializer 切换到Newtonsoft 的 JSON 转换器

我可以通过编写一个 CustomCreationConverter 来进行一次工作往返:

public class JsonDomainConverter : CustomCreationConverter<object>
{
    public JsonDomainConverter()
    {
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsInterface;
    }

    public override object Create(Type objectType)
    {
        return IocHelper.GetForType(objectType);
    }
}

No doubt this same approach is possible with JavaScriptSerializer, I just couldn't figure out how to make it work. With the Newtonsoft stuff, it took a couple hours at the most, and just a couple lines of code.

于 2011-05-09T12:44:41.587 回答