Skip to content

A Swiss Army knife for developers.

Fixes #393 - JsonToYaml error on json array (#433)

BenjaminT424246107b84
diff --git a/src/dev/impl/DevToys/DevToys.csproj b/src/dev/impl/DevToys/DevToys.csproj
index 333ce85ab..8842611ed 100644
--- a/src/dev/impl/DevToys/DevToys.csproj
+++ b/src/dev/impl/DevToys/DevToys.csproj
@@ -82,8 +82,8 @@
<Compile Include="ViewModels\Tools\Converters\ConvertersGroupToolProvider.cs" />
<Compile Include="ViewModels\Tools\EncodersDecoders\GZipEncoderDecoder\GZipEncoderDecoderToolProvider.cs" />
<Compile Include="ViewModels\Tools\EncodersDecoders\GZipEncoderDecoder\GZipEncoderDecoderToolViewModel.cs" />
- <Compile Include="ViewModels\Tools\Converters\JsonYaml\DecimalJsonConverter.cs" />
- <Compile Include="ViewModels\Tools\Converters\JsonYaml\DecimalYamlTypeResolver.cs" />
+ <Compile Include="Helpers\JsonYaml\Core\DecimalJsonConverter.cs" />
+ <Compile Include="Helpers\JsonYaml\Core\DecimalYamlTypeResolver.cs" />
<Compile Include="ViewModels\Tools\EncodersDecoders\EncodersDecodersGroupToolProvider.cs" />
<Compile Include="ViewModels\Tools\Formatters\XmlFormatter\XmlFormatterToolProvider.cs" />
<Compile Include="ViewModels\Tools\Formatters\XmlFormatter\XmlFormatterToolViewModel.cs" />
@@ -394,8 +394,8 @@
<DependentUpon>Notification.xaml</DependentUpon>
</Compile>
<Compile Include="UI\Converters\NullToVisibilityConverter.cs" />
- <Compile Include="Helpers\JsonHelper.cs" />
- <Compile Include="Helpers\YamlHelper.cs" />
+ <Compile Include="Helpers\JsonYaml\JsonHelper.cs" />
+ <Compile Include="Helpers\JsonYaml\YamlHelper.cs" />
<Compile Include="ViewModels\Tools\Converters\NumberBaseConverter\NumberBaseConverterToolProvider.cs" />
<Compile Include="ViewModels\Tools\Converters\NumberBaseConverter\NumberBaseConverterToolViewModel.cs" />
<Compile Include="ViewModels\Tools\Generators\GuidGenerator\GuidGeneratorToolProvider.cs" />
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalJsonConverter.cs b/src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalJsonConverter.cs
similarity index 91%
rename from src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalJsonConverter.cs
rename to src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalJsonConverter.cs
index 09a61ccfe..dfbbd73e1 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalJsonConverter.cs
+++ b/src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalJsonConverter.cs
@@ -1,7 +1,7 @@
using System;
using Newtonsoft.Json;
-namespace DevToys.ViewModels.Tools.Converters.JsonYaml
+namespace DevToys.Helpers.JsonYaml.Core
{
internal class DecimalJsonConverter : JsonConverter<decimal>
{
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalYamlTypeResolver.cs b/src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalYamlTypeResolver.cs
similarity index 83%
rename from src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalYamlTypeResolver.cs
rename to src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalYamlTypeResolver.cs
index 9922e7c74..1234ceb66 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/DecimalYamlTypeResolver.cs
+++ b/src/dev/impl/DevToys/Helpers/JsonYaml/Core/DecimalYamlTypeResolver.cs
@@ -4,7 +4,7 @@ using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
-namespace DevToys.ViewModels.Tools.Converters.JsonYaml
+namespace DevToys.Helpers.JsonYaml.Core
{
internal class DecimalYamlTypeResolver : INodeTypeResolver
{
@@ -14,7 +14,7 @@ namespace DevToys.ViewModels.Tools.Converters.JsonYaml
{
// avoid unnecessary parsing attempts
bool couldBeNumber =
- (scalar.Style is not ScalarStyle.SingleQuoted and not ScalarStyle.DoubleQuoted) &&
+ scalar.Style is not ScalarStyle.SingleQuoted and not ScalarStyle.DoubleQuoted &&
scalar.Value.Length != 0 &&
(scalar.Value[0] is >= '0' and <= '9' || scalar.Value[0] == '-');
diff --git a/src/dev/impl/DevToys/Helpers/JsonHelper.cs b/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs
similarity index 58%
rename from src/dev/impl/DevToys/Helpers/JsonHelper.cs
rename to src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs
index 913b9d1d6..8ba358c35 100644
--- a/src/dev/impl/DevToys/Helpers/JsonHelper.cs
+++ b/src/dev/impl/DevToys/Helpers/JsonYaml/JsonHelper.cs
@@ -4,11 +4,14 @@ using System;
using System.IO;
using System.Text;
using DevToys.Core;
+using DevToys.Helpers.JsonYaml.Core;
using DevToys.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
+using YamlDotNet.Core;
+using YamlDotNet.Serialization;
-namespace DevToys.Helpers
+namespace DevToys.Helpers.JsonYaml
{
internal static class JsonHelper
{
@@ -101,5 +104,72 @@ namespace DevToys.Helpers
return ex.Message;
}
}
+
+ /// <summary>
+ /// Convert a Yaml string to Json
+ /// </summary>
+ internal static string? ConvertFromYaml(string? input, Indentation indentationMode)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ return string.Empty;
+ }
+
+ try
+ {
+ using var stringReader = new StringReader(input);
+
+ IDeserializer deserializer = new DeserializerBuilder()
+ .WithNodeTypeResolver(new DecimalYamlTypeResolver())
+ .Build();
+
+ object? yamlObject = deserializer.Deserialize(stringReader);
+
+ if (yamlObject is null or string)
+ {
+ return null;
+ }
+
+ var stringBuilder = new StringBuilder();
+ using (var stringWriter = new StringWriter(stringBuilder))
+ using (var jsonTextWriter = new JsonTextWriter(stringWriter))
+ {
+ switch (indentationMode)
+ {
+ case Indentation.TwoSpaces:
+ jsonTextWriter.Formatting = Formatting.Indented;
+ jsonTextWriter.IndentChar = ' ';
+ jsonTextWriter.Indentation = 2;
+ break;
+
+ case Indentation.FourSpaces:
+ jsonTextWriter.Formatting = Formatting.Indented;
+ jsonTextWriter.IndentChar = ' ';
+ jsonTextWriter.Indentation = 4;
+ break;
+
+ default:
+ throw new NotSupportedException();
+ }
+
+ var jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings()
+ {
+ Converters = { new DecimalJsonConverter() }
+ });
+ jsonSerializer.Serialize(jsonTextWriter, yamlObject);
+ }
+
+ return stringBuilder.ToString();
+ }
+ catch (SemanticErrorException ex)
+ {
+ return ex.Message;
+ }
+ catch (Exception ex)
+ {
+ Logger.LogFault("Yaml to Json Converter", ex);
+ return string.Empty;
+ }
+ }
}
}
diff --git a/src/dev/impl/DevToys/Helpers/JsonYaml/YamlHelper.cs b/src/dev/impl/DevToys/Helpers/JsonYaml/YamlHelper.cs
new file mode 100644
index 000000000..491651cff
--- /dev/null
+++ b/src/dev/impl/DevToys/Helpers/JsonYaml/YamlHelper.cs
@@ -0,0 +1,109 @@
+#nullable enable
+
+using System;
+using System.Dynamic;
+using DevToys.Core;
+using DevToys.Models;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using YamlDotNet.Core;
+using YamlDotNet.Serialization;
+
+namespace DevToys.Helpers.JsonYaml
+{
+ internal static class YamlHelper
+ {
+ /// <summary>
+ /// Detects whether the given string is a valid YAML or not.
+ /// </summary>
+ internal static bool IsValidYaml(string? input)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ return false;
+ }
+
+ input = input!.Trim();
+
+ try
+ {
+ object? result = new DeserializerBuilder().Build().Deserialize<object>(input);
+ return result is not null and not string;
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Convert a Json string to Yaml
+ /// </summary>
+ internal static string? ConvertFromJson(string? input, Indentation indentationMode)
+ {
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ return string.Empty;
+ }
+
+ try
+ {
+ object? jsonObject = null;
+ var token = JToken.Parse(input!);
+ if (token is null)
+ {
+ return string.Empty;
+ }
+
+ JsonSerializerSettings defaultJsonSerializerSettings = new()
+ {
+ FloatParseHandling = FloatParseHandling.Decimal
+ };
+
+ if (token is JArray)
+ {
+ jsonObject = JsonConvert.DeserializeObject<ExpandoObject[]>(input!, defaultJsonSerializerSettings);
+ }
+ else
+ {
+ jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(input!, defaultJsonSerializerSettings);
+ }
+
+
+ if (jsonObject is not null and not string)
+ {
+ int indent = 0;
+ indent = indentationMode switch
+ {
+ Indentation.TwoSpaces => 2,
+ Indentation.FourSpaces => 4,
+ _ => throw new NotSupportedException(),
+ };
+ var serializer
+ = Serializer.FromValueSerializer(
+ new SerializerBuilder().BuildValueSerializer(),
+ EmitterSettings.Default.WithBestIndent(indent).WithIndentedSequences());
+
+ string? yaml = serializer.Serialize(jsonObject);
+ if (string.IsNullOrWhiteSpace(yaml))
+ {
+ return string.Empty;
+ }
+
+ return yaml;
+ }
+ return string.Empty;
+ }
+ catch (JsonReaderException ex)
+ {
+ return ex.Message;
+ }
+ catch (Exception ex)
+ {
+ Logger.LogFault("Yaml to Json Converter", ex);
+ return string.Empty;
+ }
+ }
+
+ }
+}
diff --git a/src/dev/impl/DevToys/Helpers/YamlHelper.cs b/src/dev/impl/DevToys/Helpers/YamlHelper.cs
deleted file mode 100644
index ffef294d2..000000000
--- a/src/dev/impl/DevToys/Helpers/YamlHelper.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-#nullable enable
-
-using System;
-using YamlDotNet.Serialization;
-
-namespace DevToys.Helpers
-{
- internal static class YamlHelper
- {
- /// <summary>
- /// Detects whether the given string is a valid YAML or not.
- /// </summary>
- internal static bool IsValidYaml(string? input)
- {
- if (string.IsNullOrWhiteSpace(input))
- {
- return false;
- }
-
- input = input!.Trim();
-
- try
- {
- object? result = new DeserializerBuilder().Build().Deserialize<object>(input);
- return result is not null and not string;
- }
- catch (Exception)
- {
- return false;
- }
- }
- }
-}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolProvider.cs
index a08044afe..2cd6e9577 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolProvider.cs
@@ -3,9 +3,9 @@
using System.Composition;
using DevToys.Shared.Api.Core;
using DevToys.Api.Tools;
-using DevToys.Helpers;
using DevToys.Core.Threading;
using Windows.UI.Xaml.Controls;
+using DevToys.Helpers.JsonYaml;
namespace DevToys.ViewModels.Tools.JsonYaml
{
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolViewModel.cs
index a9f50d23b..facb63894 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Converters/JsonYaml/JsonYamlToolViewModel.cs
@@ -2,24 +2,20 @@
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Composition;
-using System.Dynamic;
-using System.IO;
-using System.Text;
+using System.Linq;
using System.Threading.Tasks;
using DevToys.Api.Core;
using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
-using DevToys.Core;
using DevToys.Core.Threading;
+using DevToys.Helpers.JsonYaml;
+using DevToys.Models;
using DevToys.Shared.Core.Threading;
-using DevToys.Helpers;
using DevToys.Views.Tools.JsonYaml;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Newtonsoft.Json;
-using YamlDotNet.Core;
-using YamlDotNet.Serialization;
-using DevToys.ViewModels.Tools.Converters.JsonYaml;
namespace DevToys.ViewModels.Tools.JsonYaml
{
@@ -38,11 +34,11 @@ namespace DevToys.ViewModels.Tools.JsonYaml
/// <summary>
/// The indentation to apply while converting.
/// </summary>
- private static readonly SettingDefinition<string> Indentation
+ private static readonly SettingDefinition<Indentation> Indentation
= new(
name: $"{nameof(JsonYamlToolViewModel)}.{nameof(Indentation)}",
isRoaming: true,
- defaultValue: TwoSpaceIndentation);
+ defaultValue: Models.Indentation.TwoSpaces);
internal const string JsonToYaml = nameof(JsonToYaml);
internal const string YamlToJson = nameof(YamlToJson);
@@ -74,7 +70,20 @@ namespace DevToys.ViewModels.Tools.JsonYaml
/// </summary>
internal string ConversionMode
{
- get => SettingsProvider.GetSetting(Conversion);
+ get
+ {
+ string? current = SettingsProvider.GetSetting(Conversion);
+ if (string.IsNullOrWhiteSpace(current) ||
+ string.Equals(current, JsonToYaml, StringComparison.Ordinal))
+ {
+ InputValueLanguage = "json";
+ OutputValueLanguage = "yaml";
+ return JsonToYaml;
+ }
+ InputValueLanguage = "yaml";
+ OutputValueLanguage = "json";
+ return YamlToJson;
+ }
set
{
if (!_setPropertyInProgress)
@@ -116,20 +125,33 @@ namespace DevToys.ViewModels.Tools.JsonYaml
/// <summary>
/// Gets or sets the desired indentation.
/// </summary>
- internal string IndentationMode
+ internal IndentationDisplayPair IndentationMode
{
- get => SettingsProvider.GetSetting(Indentation);
+ get
+ {
+ Indentation settingsValue = SettingsProvider.GetSetting(Indentation);
+ IndentationDisplayPair? indentation = Indentations.FirstOrDefault(x => x.Value == settingsValue);
+ return indentation ?? IndentationDisplayPair.TwoSpaces;
+ }
set
{
- if (!string.Equals(SettingsProvider.GetSetting(Indentation), value, StringComparison.Ordinal))
+ if (IndentationMode != value)
{
- SettingsProvider.SetSetting(Indentation, value);
+ SettingsProvider.SetSetting(Indentation, value.Value);
OnPropertyChanged();
QueueConversion();
}
}
}
+ /// <summary>
+ /// Get a list of supported Indentation
+ /// </summary>
+ internal IReadOnlyList<IndentationDisplayPair> Indentations = new ObservableCollection<IndentationDisplayPair> {
+ Models.IndentationDisplayPair.TwoSpaces,
+ Models.IndentationDisplayPair.FourSpaces
+ };
+
/// <summary>
/// Gets or sets the input text.
/// </summary>
@@ -200,22 +222,29 @@ namespace DevToys.ViewModels.Tools.JsonYaml
while (_conversionQueue.TryDequeue(out string? text))
{
- bool success;
- string result;
+ string? result;
if (string.Equals(ConversionMode, JsonToYaml, StringComparison.Ordinal))
{
- success = ConvertJsonToYaml(text, out result);
+ result = YamlHelper.ConvertFromJson(text, IndentationMode.Value);
+ if (string.IsNullOrEmpty(result))
+ {
+ result = Strings.InvalidYaml;
+ }
}
else
{
- success = ConvertYamlToJson(text, out result);
+ result = JsonHelper.ConvertFromYaml(text, IndentationMode.Value);
+ if (string.IsNullOrEmpty(result))
+ {
+ result = Strings.InvalidYaml;
+ }
}
ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>
{
OutputValue = result;
- if (success && !_toolSuccessfullyWorked)
+ if (!string.IsNullOrWhiteSpace(result) && !_toolSuccessfullyWorked)
{
_toolSuccessfullyWorked = true;
_marketingService.NotifyToolSuccessfullyWorked();
@@ -225,119 +254,5 @@ namespace DevToys.ViewModels.Tools.JsonYaml
_conversionInProgress = false;
}
-
- private bool ConvertJsonToYaml(string input, out string output)
- {
- if (string.IsNullOrWhiteSpace(input))
- {
- output = string.Empty;
- return false;
- }
-
- try
- {
- dynamic? jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(input, _defaultJsonSerializerSettings);
- if (jsonObject is not null and not string)
- {
- int indent = 0;
- indent = IndentationMode switch
- {
- TwoSpaceIndentation => 2,
- FourSpaceIndentation => 4,
- _ => throw new NotSupportedException(),
- };
- var serializer
- = Serializer.FromValueSerializer(
- new SerializerBuilder().BuildValueSerializer(),
- EmitterSettings.Default.WithBestIndent(indent).WithIndentedSequences());
-
- string? yaml = serializer.Serialize(jsonObject);
- output = yaml ?? string.Empty;
- return true;
- }
-
- output = string.Empty;
- }
- catch (JsonReaderException ex)
- {
- output = ex.Message;
- }
- catch (Exception ex)
- {
- Logger.LogFault("Json to Yaml Converter", ex);
- output = string.Empty;
- }
-
- return false;
- }
-
- private bool ConvertYamlToJson(string input, out string output)
- {
- if (string.IsNullOrWhiteSpace(input))
- {
- output = string.Empty;
- return false;
- }
-
- try
- {
- using var stringReader = new StringReader(input);
-
- var deserializer = new DeserializerBuilder()
- .WithNodeTypeResolver(new DecimalYamlTypeResolver())
- .Build();
-
- object? yamlObject = deserializer.Deserialize(stringReader);
-
- if (yamlObject is null or string)
- {
- output = Strings.InvalidYaml;
- return false;
- }
-
- var stringBuilder = new StringBuilder();
- using (var stringWriter = new StringWriter(stringBuilder))
- using (var jsonTextWriter = new JsonTextWriter(stringWriter))
- {
- switch (IndentationMode)
- {
- case TwoSpaceIndentation:
- jsonTextWriter.Formatting = Formatting.Indented;
- jsonTextWriter.IndentChar = ' ';
- jsonTextWriter.Indentation = 2;
- break;
-
- case FourSpaceIndentation:
- jsonTextWriter.Formatting = Formatting.Indented;
- jsonTextWriter.IndentChar = ' ';
- jsonTextWriter.Indentation = 4;
- break;
-
- default:
- throw new NotSupportedException();
- }
-
- var jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings()
- {
- Converters = { new DecimalJsonConverter() }
- });
- jsonSerializer.Serialize(jsonTextWriter, yamlObject);
- }
-
- output = stringBuilder.ToString();
- return true;
- }
- catch (SemanticErrorException ex)
- {
- output = ex.Message;
- }
- catch (Exception ex)
- {
- Logger.LogFault("Yaml to Json Converter", ex);
- output = string.Empty;
- }
-
- return false;
- }
}
}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs
index 3a4e3f8c0..c2c36181d 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs
@@ -9,10 +9,10 @@ using DevToys.Api.Core;
using DevToys.Api.Tools;
using DevToys.Core.Threading;
using DevToys.Shared.Core.Threading;
-using DevToys.Helpers;
using DevToys.Models;
using DevToys.Views.Tools.JwtDecoderEncoder;
using Microsoft.Toolkit.Mvvm.ComponentModel;
+using DevToys.Helpers.JsonYaml;
namespace DevToys.ViewModels.Tools.JwtDecoderEncoder
{
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolProvider.cs
index 029fb39f9..b3d7d1874 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolProvider.cs
@@ -3,9 +3,9 @@
using System.Composition;
using DevToys.Shared.Api.Core;
using DevToys.Api.Tools;
-using DevToys.Helpers;
using DevToys.Core.Threading;
using Windows.UI.Xaml.Controls;
+using DevToys.Helpers.JsonYaml;
namespace DevToys.ViewModels.Tools.JsonFormatter
{
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs
index 22c5fa8a9..fc816be36 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Formatters/JsonFormatter/JsonFormatterToolViewModel.cs
@@ -11,10 +11,10 @@ using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
using DevToys.Core.Threading;
using DevToys.Shared.Core.Threading;
-using DevToys.Helpers;
using DevToys.Models;
using DevToys.Views.Tools.JsonFormatter;
using Microsoft.Toolkit.Mvvm.ComponentModel;
+using DevToys.Helpers.JsonYaml;
namespace DevToys.ViewModels.Tools.JsonFormatter
{
diff --git a/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml
index 1d057b747..22c9177f5 100644
--- a/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml
@@ -58,10 +58,9 @@
<FontIcon Glyph="&#xF6F8;" />
</controls:ExpandableSettingControl.Icon>
<ComboBox
- SelectedValuePath="Tag"
+ ItemsSource="{x:Bind ViewModel.Indentations}"
+ DisplayMemberPath="DisplayName"
SelectedValue="{x:Bind ViewModel.IndentationMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
- <ComboBoxItem Tag="TwoSpaces" Content="{x:Bind ViewModel.Strings.TwoSpaces}"/>
- <ComboBoxItem Tag="FourSpaces" Content="{x:Bind ViewModel.Strings.FourSpaces}"/>
</ComboBox>
</controls:ExpandableSettingControl>
</StackPanel>
diff --git a/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml.cs
index 004015972..3fab2099a 100644
--- a/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml.cs
+++ b/src/dev/impl/DevToys/Views/Tools/Converters/JsonYaml/JsonYamlToolPage.xaml.cs
@@ -1,7 +1,7 @@
#nullable enable
using DevToys.Api.Core.Navigation;
-using DevToys.Helpers;
+using DevToys.Helpers.JsonYaml;
using DevToys.Shared.Core;
using DevToys.ViewModels.Tools.JsonYaml;
using Windows.UI.Xaml;
diff --git a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
index 41d337249..5e5eef23d 100644
--- a/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
+++ b/src/tests/DevToys.Tests/Helpers/JsonHelperTests.cs
@@ -1,4 +1,4 @@
-using DevToys.Helpers;
+using DevToys.Helpers.JsonYaml;
using DevToys.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -64,5 +64,59 @@ namespace DevToys.Tests.Helpers
{
Assert.AreEqual(expectedResult, JsonHelper.Format(input, Indentation.Minified));
}
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ public void ConvertFromYamlShouldReturnEmptyString(string input, string expected)
+ {
+ // prepare & act
+ string actual = JsonHelper.ConvertFromYaml(input, Indentation.FourSpaces);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [TestMethod("Convert From Yaml with unsupported Indentation")]
+ public void ConvertFromYamlWithUnsupportedIndentationShouldReturnEmptyString()
+ {
+ // prepare
+ string input = "- key: value";
+ string expected = string.Empty;
+
+ // act
+ string actual = JsonHelper.ConvertFromYaml(input, Indentation.Minified);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [TestMethod("Convert From Yaml with unsupported yaml")]
+ public void ConvertFromYamlWithUnsupportedYamlShouldExceptionMessage()
+ {
+ // prepare
+ string input = "[";
+ string expected = "(Line: 2, Col: 1, Idx: 1) - (Line: 2, Col: 1, Idx: 1): While parsing a node, did not find expected node content.";
+
+ // act
+ string actual = JsonHelper.ConvertFromYaml(input, Indentation.Minified);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [DataTestMethod]
+ [DataRow(" - key: value ", "[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]")]
+ [DataRow(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]
+ public void ConvertFromYamlWithTwoSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.ConvertFromYaml(input, Indentation.TwoSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow(" - key: value ", "[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]")]
+ [DataRow(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]
+ public void ConvertFromYamlWithFourSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, JsonHelper.ConvertFromYaml(input, Indentation.FourSpaces));
+ }
}
}
diff --git a/src/tests/DevToys.Tests/Helpers/YamlHelperTests.cs b/src/tests/DevToys.Tests/Helpers/YamlHelperTests.cs
index 0bea4039f..d58b97a45 100644
--- a/src/tests/DevToys.Tests/Helpers/YamlHelperTests.cs
+++ b/src/tests/DevToys.Tests/Helpers/YamlHelperTests.cs
@@ -1,4 +1,5 @@
-using DevToys.Helpers;
+using DevToys.Helpers.JsonYaml;
+using DevToys.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DevToys.Tests.Helpers
@@ -16,5 +17,76 @@ namespace DevToys.Tests.Helpers
{
Assert.AreEqual(expectedResult, YamlHelper.IsValidYaml(input));
}
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow("", "")]
+ [DataRow(" ", "")]
+ public void ConvertFromJsonShouldReturnEmptyString(string input, string expected)
+ {
+ // prepare & act
+ string actual = YamlHelper.ConvertFromJson(input, Indentation.FourSpaces);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [TestMethod("Convert From Json with unsupported Indentation")]
+ public void ConvertFromJsonWithUnsupportedIndentationShouldReturnEmptyString()
+ {
+ // prepare
+ string input = "{}";
+ string expected = string.Empty;
+
+ // act
+ string actual = YamlHelper.ConvertFromJson(input, Indentation.Minified);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [TestMethod("Convert From Json with unsupported Json")]
+ public void ConvertFromJsonWithUnsupportedJsonShouldExceptionMessage()
+ {
+ // prepare
+ string input = "-";
+ string expected = "Input string '-' is not a valid number. Path '', line 1, position 1.";
+
+ // act
+ string actual = YamlHelper.ConvertFromJson(input, Indentation.Minified);
+
+ Assert.AreEqual(expected, actual);
+ }
+
+ [DataTestMethod]
+ [DataRow("{\r\n \"key\": \"value\"\r\n }", "key: value\r\n")]
+ [DataRow("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]
+ public void ConvertFromJsonWithTwoSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, YamlHelper.ConvertFromJson(input, Indentation.TwoSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow("{\r\n \"key\": \"value\"\r\n }", "key: value\r\n")]
+ [DataRow("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]
+ public void ConvertFromJsonWithFourSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, YamlHelper.ConvertFromJson(input, Indentation.FourSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow("[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]", "- key: value\r\n")]
+ [DataRow("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]
+ public void ConvertFromJsonWithJsonRootArrayWithTwoSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, YamlHelper.ConvertFromJson(input, Indentation.TwoSpaces));
+ }
+
+ [DataTestMethod]
+ [DataRow("[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]", "- key: value\r\n")]
+ [DataRow("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]
+ public void ConvertFromJsonWithJsonRootArrayWithFourSpaces(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, YamlHelper.ConvertFromJson(input, Indentation.FourSpaces));
+ }
+
}
}