Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
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