This repository has been archived by the owner on Apr 26, 2020. It is now read-only.
/
JsonNetSerializer.cs
65 lines (59 loc) · 2.36 KB
/
JsonNetSerializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
namespace Nancy.Serialization.JsonNet
{
using System.Collections.Generic;
using System.IO;
using Nancy.IO;
using Newtonsoft.Json;
using Responses.Negotiation;
public class JsonNetSerializer : ISerializer
{
private readonly JsonSerializer serializer;
/// <summary>
/// Initializes a new instance of the <see cref="JsonNetSerializer"/> class.
/// </summary>
public JsonNetSerializer()
{
this.serializer = JsonSerializer.CreateDefault();
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonNetSerializer"/> class,
/// with the provided <paramref name="serializer"/>.
/// </summary>
/// <param name="serializer">Json converters used when serializing.</param>
public JsonNetSerializer(JsonSerializer serializer)
{
this.serializer = serializer;
}
/// <summary>
/// Whether the serializer can serialize the content type
/// </summary>
/// <param name="mediaRange">Content type to serialise</param>
/// <returns>True if supported, false otherwise</returns>
public bool CanSerialize(MediaRange mediaRange)
{
return Helpers.IsJsonType(mediaRange);
}
/// <summary>
/// Gets the list of extensions that the serializer can handle.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
public IEnumerable<string> Extensions
{
get { yield return "json"; }
}
/// <summary>
/// Serialize the given model with the given contentType
/// </summary>
/// <param name="mediaRange">Content type to serialize into</param>
/// <param name="model">Model to serialize</param>
/// <param name="outputStream">Output stream to serialize to</param>
/// <returns>Serialised object</returns>
public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)
{
using (var writer = new JsonTextWriter(new StreamWriter(new UnclosableStreamWrapper(outputStream))))
{
this.serializer.Serialize(writer, model);
}
}
}
}