|
| 1 | +namespace Nest |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using Newtonsoft.Json; |
| 5 | + |
| 6 | + /// <summary> |
| 7 | + /// Converter for converting Uri to String and vica versa |
| 8 | + /// </summary> |
| 9 | + /// <remarks> |
| 10 | + /// Code originated from http://stackoverflow.com/a/8087049/106909 |
| 11 | + /// </remarks> |
| 12 | + public sealed class UriJsonConverter : JsonConverter |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// Determines whether this instance can convert the specified object type. |
| 16 | + /// </summary> |
| 17 | + /// <param name="objectType"></param> |
| 18 | + /// <returns></returns> |
| 19 | + public override bool CanConvert(Type objectType) |
| 20 | + { |
| 21 | + return objectType == typeof(Uri); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Reads the JSON representation of the object. |
| 26 | + /// </summary> |
| 27 | + /// <param name="reader"></param> |
| 28 | + /// <param name="objectType"></param> |
| 29 | + /// <param name="existingValue"></param> |
| 30 | + /// <param name="serializer"></param> |
| 31 | + /// <returns></returns> |
| 32 | + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
| 33 | + { |
| 34 | + if (reader.TokenType == JsonToken.String) |
| 35 | + return new Uri((string)reader.Value); |
| 36 | + |
| 37 | + if (reader.TokenType == JsonToken.Null) |
| 38 | + return null; |
| 39 | + |
| 40 | + throw new InvalidOperationException("Unhandled case for UriConverter. Check to see if this converter has been applied to the wrong serialization type."); |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Writes the JSON representation of the object. |
| 45 | + /// </summary> |
| 46 | + /// <param name="writer"></param> |
| 47 | + /// <param name="value"></param> |
| 48 | + /// <param name="serializer"></param> |
| 49 | + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
| 50 | + { |
| 51 | + if (null == value) |
| 52 | + { |
| 53 | + writer.WriteNull(); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + var uriValue = value as Uri; |
| 58 | + if (uriValue != null) |
| 59 | + { |
| 60 | + writer.WriteValue(uriValue.OriginalString); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + throw new InvalidOperationException("Unhandled case for UriConverter. Check to see if this converter has been applied to the wrong serialization type."); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments