Skip to content

Commit

Permalink
#75 Added new method that allow a user to retrieve the appropriate se…
Browse files Browse the repository at this point in the history
…rializer from a type which can either be an interface, concrete class, array or IEnumerable
  • Loading branch information
linvi committed Aug 14, 2016
1 parent d368fac commit 0b938ef
Showing 1 changed file with 38 additions and 5 deletions.
43 changes: 38 additions & 5 deletions Tweetinvi/JsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ public static string ToJson<T>(this T obj) where T : class
var type = typeof(T);
object toSerialize = obj;

var serializer = GetSerializer(type);
var serializer = GetSerializerFromNonCollectionType(type);

if (serializer != null)
{
toSerialize = _getSerializableObject[type].GetSerializableObject(obj);
toSerialize = serializer.GetSerializableObject(obj);
}
else if (obj is IEnumerable && type.IsGenericType)
{
Expand All @@ -110,7 +110,7 @@ public static string ToJson<T>(this T obj) where T : class
genericType = type.GetElementType();
}

serializer = GetSerializer(genericType);
serializer = GetSerializerFromNonCollectionType(genericType);

if (serializer != null)
{
Expand Down Expand Up @@ -142,7 +142,7 @@ public static T ConvertJsonTo<T>(this string json) where T : class

try
{
var serializer = GetSerializer(type);
var serializer = GetSerializerFromNonCollectionType(type);
if (serializer != null)
{
return serializer.GetDeserializedObject(json) as T;
Expand All @@ -161,7 +161,7 @@ public static T ConvertJsonTo<T>(this string json) where T : class
genericType = type.GetElementType();
}

serializer = GetSerializer(genericType);
serializer = GetSerializerFromNonCollectionType(genericType);
if (genericType != null && serializer != null)
{
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(genericType));
Expand Down Expand Up @@ -195,11 +195,44 @@ public static T ConvertJsonTo<T>(this string json) where T : class

private static IJsonSerializer GetSerializer(Type type)
{
var serializer = GetSerializerFromNonCollectionType(type);

if (serializer != null)
{
return serializer;
}

if (typeof(IEnumerable).IsAssignableFrom(type))
{
Type genericType = null;

if (type.IsGenericType)
{
genericType = type.GetGenericArguments()[0];
}
else if (typeof(Array).IsAssignableFrom(type))
{
genericType = type.GetElementType();
}

if (genericType != null)
{
return GetSerializerFromNonCollectionType(genericType);
}
}

return null;
}

private static IJsonSerializer GetSerializerFromNonCollectionType(Type type)
{
// Test interfaces
if (_getSerializableObject.ContainsKey(type))
{
return _getSerializableObject[type];
}

// Test concrete classes from mapped interfaces
if (_getSerializableObject.Keys.Any(x => x.IsAssignableFrom(type)))
{
return _getSerializableObject.FirstOrDefault(x => x.Key.IsAssignableFrom(type)).Value;
Expand Down

0 comments on commit 0b938ef

Please sign in to comment.