Last active
August 29, 2015 13:56
-
-
Save BobReid/8960146 to your computer and use it in GitHub Desktop.
OpenRasta JSON.Net Codec
This file contains 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
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