Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonHelper.IsValid is not matching some JSON structures #363

Merged
merged 1 commit into from
Feb 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 16 additions & 24 deletions src/dev/impl/DevToys/Helpers/JsonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,26 @@ internal static class JsonHelper
/// </summary>
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;
}
}
Expand All @@ -54,14 +46,14 @@ internal static bool IsValid(string? input)
/// </summary>
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();
Expand Down
4 changes: 3 additions & 1 deletion src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down