Skip to content

Instantly share code, notes, and snippets.

@Yortw
Last active August 30, 2015 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yortw/6c7d8927af289fd4f5c3 to your computer and use it in GitHub Desktop.
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
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