From 498765d1b0a6b4516673cb6fbfd5807953fe164f Mon Sep 17 00:00:00 2001 From: Tobias Klika Date: Mon, 25 Nov 2013 22:12:34 +0100 Subject: [PATCH] add Uri converter --- UptimeSharp/Models/Monitor.cs | 32 ++++--------------------- UptimeSharp/Utilities/JsonExtensions.cs | 32 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/UptimeSharp/Models/Monitor.cs b/UptimeSharp/Models/Monitor.cs index 9789040..444ae7e 100644 --- a/UptimeSharp/Models/Monitor.cs +++ b/UptimeSharp/Models/Monitor.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; +using Newtonsoft.Json; using PropertyChanged; +using System; +using System.Collections.Generic; namespace UptimeSharp.Models { @@ -30,15 +30,6 @@ namespace UptimeSharp.Models [JsonProperty("friendlyname")] public string Name { get; set; } - /// - /// Gets or sets the URI. - /// - /// - /// The URI. - /// - [JsonProperty("url")] - public string UriString { get; set; } - /// /// Gets the URI. /// @@ -46,22 +37,7 @@ namespace UptimeSharp.Models /// The URI. /// [JsonIgnore] - public Uri Uri - { - get - { - Uri uri; - try - { - uri = new Uri(UriString); - } - catch - { - uri = null; - } - return uri; - } - } + public Uri Uri { get; set; } /// /// Gets or sets the port. diff --git a/UptimeSharp/Utilities/JsonExtensions.cs b/UptimeSharp/Utilities/JsonExtensions.cs index cef2a05..a73a51d 100644 --- a/UptimeSharp/Utilities/JsonExtensions.cs +++ b/UptimeSharp/Utilities/JsonExtensions.cs @@ -45,4 +45,36 @@ namespace UptimeSharp return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(reader.Value)).ToLocalTime(); } } + + + + public class UriConverter : JsonConverter + { + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.String && Uri.IsWellFormedUriString(reader.Value.ToString(), UriKind.Absolute)) + { + return new Uri(reader.Value.ToString()); + } + + return null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull(); + } + else if (value is Uri) + { + writer.WriteValue(((Uri)value).OriginalString); + } + } + + public override bool CanConvert(Type objectType) + { + return objectType.Equals(typeof(Uri)); + } + } }