/
UriConverter.cs
43 lines (37 loc) · 1.37 KB
/
UriConverter.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
using Bayat.Json.Serialization;
using System;
namespace Bayat.Json.Converters
{
public class UriConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Uri);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializerReader internalReader)
{
switch (reader.TokenType)
{
case JsonToken.String:
return new Uri((string)reader.Value);
case JsonToken.Null:
return null;
}
throw new InvalidOperationException("Unhandled case for UriConverter. Check to see if this converter has been applied to the wrong serialization type.");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializerWriter internalWriter)
{
if (null == value)
{
writer.WriteNull();
return;
}
var uri = value as Uri;
if (uri == null)
throw new InvalidOperationException(
"Unhandled case for UriConverter. Check to see if this converter has been applied to the wrong serialization type.");
writer.WriteValue(uri.OriginalString);
return;
}
}
}