开发者

Dependency Injection and JavaScriptConverter.Deserialize

开发者 https://www.devze.com 2023-03-03 16:49 出处:网络
My application needs to combine extensive use of dependency inje开发者_StackOverflowction with the use of JSON as a public API.This apparently leads to the need for a custom JavaScriptConverter.

My application needs to combine extensive use of dependency inje开发者_StackOverflowction with the use of JSON as a public API. This apparently leads to the need for a custom JavaScriptConverter.

Right now, my JavaScriptConverter's Deserialize method looks like this:

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

This hands back the appropriate class. Unfortunately, it fails to populate the class members with the applicable values. What I'm missing is a way to tell the Serializer, "Here's the type you asked for. Now fill it in."


The solution I used was to switch from JavaScriptSerializer to Newtonsoft's JSON converter

I was able to get a working round trip by writing a single 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消