Skip to content

Commit

Permalink
Fix in YAML to JSON involving boolean conversion (#579)
Browse files Browse the repository at this point in the history
  • Loading branch information
veler authored Jul 9, 2022
1 parent 09d33f7 commit f842c4d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/dev/impl/DevToys/DevToys.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<Compile Include="Core\OOP\AppService.cs" />
<Compile Include="Core\QueueWorkerViewModelBase.cs" />
<Compile Include="Core\Threading\AsyncLazy.cs" />
<Compile Include="Helpers\JsonYaml\Core\BooleanYamlTypeResolver.cs" />
<Compile Include="Helpers\StorageFileHelper.cs" />
<Compile Include="Helpers\ImageHelper.cs" />
<Compile Include="Helpers\ColorBlindnessSimulatorHelper.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#nullable enable

using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

namespace DevToys.Helpers.JsonYaml.Core
{
internal class BooleanYamlTypeResolver : INodeTypeResolver
{
public bool Resolve(NodeEvent? nodeEvent, ref Type currentType)
{
if (nodeEvent is Scalar scalar)
{
// avoid unnecessary parsing attempts
bool couldBeBoolean
= scalar.Style is ScalarStyle.Plain
&& (string.Equals(scalar.Value, bool.FalseString, StringComparison.OrdinalIgnoreCase) || string.Equals(scalar.Value, bool.TrueString, StringComparison.OrdinalIgnoreCase));

if (couldBeBoolean && bool.TryParse(scalar.Value, out _))
{
currentType = typeof(bool);
return true;
}
}
return false;
}
}
}
1 change: 1 addition & 0 deletions src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ internal static string Format(string? input, Indentation indentationMode, bool s

IDeserializer deserializer = new DeserializerBuilder()
.WithNodeTypeResolver(new DecimalYamlTypeResolver())
.WithNodeTypeResolver(new BooleanYamlTypeResolver())
.Build();

object? yamlObject = deserializer.Deserialize(stringReader);
Expand Down

0 comments on commit f842c4d

Please sign in to comment.