Skip to content

Instantly share code, notes, and snippets.

@BobReid
Last active August 29, 2015 13:56
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 BobReid/8960146 to your computer and use it in GitHub Desktop.
Save BobReid/8960146 to your computer and use it in GitHub Desktop.
OpenRasta JSON.Net Codec
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenRasta.Codecs;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
namespace Reider.Web.Codecs
{
// A JSON Codec for OpenRasta that uses the JSON.Net serializer
public class JsonNetCodec : IMediaTypeReader, IMediaTypeWriter
{
public object Configuration { get; set; }
private JsonSerializerSettings settings;
private JsonSerializerSettings Settings
{
get
{
//Setup whatever settings you'd like.
//IsoDateTimeConverter allows for string formatted dates
if (settings == null)
{
settings = new Newtonsoft.Json.JsonSerializerSettings();
settings.Converters.Add(new IsoDateTimeConverter());
settings.Converters.Add(new StringEnumConverter());
settings.NullValueHandling = NullValueHandling.Ignore;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
#if DEBUG
settings.Formatting = Formatting.Indented;
#endif
}
return settings;
}
}
public object ReadFrom(OpenRasta.Web.IHttpEntity request, OpenRasta.TypeSystem.IType destinationType, string destinationName)
{
using (var streamReader = new StreamReader(request.Stream))
{
var serializer = JsonSerializer.Create(Settings);
return serializer.Deserialize(streamReader, destinationType.StaticType);
}
}
public void WriteTo(object entity, OpenRasta.Web.IHttpEntity response, string[] codecParameters)
{
using (var streamWriter = new StreamWriter(response.Stream))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
var serializer = JsonSerializer.Create(Settings);
serializer.Serialize(jsonWriter, entity);
jsonWriter.Flush();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment