From 2d678fdc0a013d0e2d8e43c15987bfd1346e3277 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Loi=CC=88c=20Wolff?= Date: Sun, 8 Apr 2018 19:32:19 +0200 Subject: [PATCH] changed `WriteJsonValue` to switch with pattern --- Ooui/JsonConvert.cs | 92 +++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 53 deletions(-) diff --git a/Ooui/JsonConvert.cs b/Ooui/JsonConvert.cs index 1eddd06..8646262 100644 --- a/Ooui/JsonConvert.cs +++ b/Ooui/JsonConvert.cs @@ -2,6 +2,8 @@ namespace Ooui { + using static System.FormattableString; + class JsonConvert { public static void WriteJsonString (System.IO.TextWriter w, string s) @@ -36,60 +38,44 @@ namespace Ooui public static void WriteJsonValue (System.IO.TextWriter w, object value) { - if (value == null) { - w.Write ("null"); - return; + switch(value) { + case string s: + WriteJsonString (w, s); + break; + case Array a: + w.Write ('['); + var head = ""; + foreach (var o in a) { + w.Write (head); + WriteJsonValue (w, o); + head = ","; + } + w.Write (']'); + break; + case EventTarget e: + w.Write ('\"'); + w.Write (e.Id); + w.Write ('\"'); + break; + case Color c: + WriteJsonString (w, c.ToString()); + break; + case double d: + w.Write (Invariant ($"{d}")); + break; + case int i: + w.Write (Invariant ($"{i}")); + break; + case float f: + w.Write (Invariant ($"{f}")); + break; + case null: + w.Write ("null"); + break; + default: + w.Write (Newtonsoft.Json.JsonConvert.SerializeObject (value)); + break; } - var s = value as string; - if (s != null) { - WriteJsonString (w, s); - return; - } - - var a = value as Array; - if (a != null) { - w.Write ('['); - var head = ""; - foreach (var o in a) { - w.Write (head); - WriteJsonValue (w, o); - head = ","; - } - w.Write (']'); - return; - } - - var e = value as EventTarget; - if (e != null) { - w.Write ('\"'); - w.Write (e.Id); - w.Write ('\"'); - return; - } - - if (value is Color) { - WriteJsonString (w, ((Color)value).ToString ()); - return; - } - - var icult = System.Globalization.CultureInfo.InvariantCulture; - - if (value is double) { - w.Write (((double)value).ToString (icult)); - return; - } - - if (value is int) { - w.Write (((int)value).ToString (icult)); - return; - } - - if (value is float) { - w.Write (((float)value).ToString (icult)); - return; - } - - w.Write (Newtonsoft.Json.JsonConvert.SerializeObject (value)); } public static string SerializeObject (object value)