From f7d8d4a09eba027d7190e87c747c06673bf809fd Mon Sep 17 00:00:00 2001 From: Anirudh Khanna Date: Wed, 9 Feb 2022 20:14:29 +0530 Subject: [PATCH] JsonHelper.IsValid is not matching some JSON structures --- src/dev/impl/DevToys/Helpers/JsonHelper.cs | 40 ++++++++----------- .../DevToys.Tests/Helpers/JsonHelperTests.cs | 4 +- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/src/dev/impl/DevToys/Helpers/JsonHelper.cs b/src/dev/impl/DevToys/Helpers/JsonHelper.cs index 84e3ae930a..913b9d1d67 100644 --- a/src/dev/impl/DevToys/Helpers/JsonHelper.cs +++ b/src/dev/impl/DevToys/Helpers/JsonHelper.cs @@ -17,34 +17,26 @@ internal static class JsonHelper /// internal static bool IsValid(string? input) { - if (string.IsNullOrWhiteSpace(input)) + input = input?.Trim(); + + if (input == null) { - return false; + return true; } - input = input!.Trim(); - - if ((input.StartsWith("{") && input.EndsWith("}")) //For object - || (input.StartsWith("[") && input.EndsWith("]"))) //For array + try { - try - { - var jtoken = JToken.Parse(input); - return jtoken is not null; - } - catch (JsonReaderException) - { - // Exception in parsing json. It likely mean the text isn't a JSON. - return false; - } - catch (Exception ex) //some other exception - { - Logger.LogFault("Check is string if JSON", ex); - return false; - } + var jtoken = JToken.Parse(input); + return jtoken is not null; } - else + catch (JsonReaderException) + { + // Exception in parsing json. It likely mean the text isn't a JSON. + return false; + } + catch (Exception ex) //some other exception { + Logger.LogFault("Check if string is JSON", ex); return false; } } @@ -54,14 +46,14 @@ internal static bool IsValid(string? input) /// internal static string Format(string? input, Indentation indentationMode) { - if (!IsValid(input)) + if (input == null || !IsValid(input)) { return string.Empty; } try { - var jtoken = JToken.Parse(input!); + var jtoken = JToken.Parse(input); if (jtoken is not null) { var stringBuilder = new StringBuilder(); diff --git a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs index b83ef28c19..41d337249f 100644 --- a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs +++ b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs @@ -8,7 +8,9 @@ namespace DevToys.Tests.Helpers public class JsonHelperTests { [DataTestMethod] - [DataRow(null, false)] + [DataRow(null, true)] + [DataRow("\"foo\"", true)] + [DataRow("123", true)] [DataRow("", false)] [DataRow(" ", false)] [DataRow(" { } ", true)]