For my .NET/C# project, I need to use a JSON library but I should be dependent on a specific implementation. I know that there are plenty of JSON *c#* libraries out there like Json.NET, FastJson, Simple Json (simplejson.codeplex.com), e开发者_StackOverflowtc. Now how should I abstract away different implementations so that I will be able to switch libraries in a future time. I have no control on other libraries but I have full control on my project. Looking for your opinions.
Depending on your needs you can create a single entry point to whatever library you wish to use.
public static class Json
{
public static string Serialize(object o)
{
// ...
}
public static T Deserialize<T>(string s)
{
// ...
}
}
One way to do this would be to create an interface that all libraries have the capability of matching, then implementing a wrapper class for each that implements the interface using that particular library. Each wrapper class will have to be in a separate assembly to avoid a dependency on the wrapper class's library.
Then, when you choose an implementation at runtime, you'll do it by instantiating the wrapper class through reflection.
Best way is to create an interface.
Here is how we do it in Facebook C# SDK (http://facebooksdk.codeplex.com)
public interface IJsonSerializer
{
string SerializeObject(object obj);
object DeserializeObject(string json, Type type);
T DeserializeObject<T>(string json);
object DeserializeObject(string json);
}
精彩评论