Last active
August 30, 2015 02:35
-
-
Save Yortw/6c7d8927af289fd4f5c3 to your computer and use it in GitHub Desktop.
A Json.Net converter for IEnumerator<T> types, serialises enumerator results as a json array. Great when you need to include type information in serialised data but want to return raw linq results for controller actions, instead of calling toarray/tolist. See http://www.yortondotnet.com/2015/08/getting-lazy-with-linq-jsonnet-and.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class JsonEnumerableConverter : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
if (!objectType.IsGenericType) return false; | |
var genericType = objectType.GenericTypeArguments.First(); | |
var enumeratorType = typeof(IEnumerator<>).MakeGenericType(genericType); | |
return (objectType.GetInterface(enumeratorType.Name) != null); | |
} | |
public override bool CanRead | |
{ | |
get | |
{ | |
return false; | |
} | |
} | |
public override bool CanWrite | |
{ | |
get | |
{ | |
return true; | |
} | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
return null; | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
writer.WriteStartArray(); | |
foreach (var item in (IEnumerable)value) | |
{ | |
serializer.Serialize(writer, item); | |
} | |
writer.WriteEndArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment