From e2cd8633b921c764ed85a6c623272dba2e0dd302 Mon Sep 17 00:00:00 2001 From: Shuai Yuan <128874481+shuaiyuanxx@users.noreply.github.com> Date: Thu, 19 Dec 2024 16:52:12 +0800 Subject: [PATCH] [Bug fix] Add a format validation step before format conversion. (#36404) This PR aims to fix the bug #35225 by introducing a new method IsJson to determine if a given text is in JSON format. The IsJson method is then utilized in the ToJsonFromXmlOrCsvAsync method to optimize the processing logic. If the text is already in JSON format, it is returned directly without further conversion from XML or CSV. Co-authored-by: Heiko <61519853+htcfreek@users.noreply.github.com> --------- Signed-off-by: Shawn Yuan Co-authored-by: Heiko <61519853+htcfreek@users.noreply.github.com> --- .../AdvancedPaste/Helpers/JsonHelper.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/modules/AdvancedPaste/AdvancedPaste/Helpers/JsonHelper.cs b/src/modules/AdvancedPaste/AdvancedPaste/Helpers/JsonHelper.cs index 2aed82f1b3..8329e15230 100644 --- a/src/modules/AdvancedPaste/AdvancedPaste/Helpers/JsonHelper.cs +++ b/src/modules/AdvancedPaste/AdvancedPaste/Helpers/JsonHelper.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; @@ -33,6 +34,19 @@ namespace AdvancedPaste.Helpers private static readonly Regex CsvRemoveStartAndEndQuotationMarksRegex = new Regex(@"^""(?=(""{2})+)|(?<=(""{2})+)""$"); private static readonly Regex CsvReplaceDoubleQuotationMarksRegex = new Regex(@"""{2}"); + private static bool IsJson(string text) + { + try + { + _ = JsonDocument.Parse(text); + return true; + } + catch (Exception) + { + return false; + } + } + internal static async Task ToJsonFromXmlOrCsvAsync(DataPackageView clipboardData) { Logger.LogTrace(); @@ -46,6 +60,12 @@ namespace AdvancedPaste.Helpers var text = await clipboardData.GetTextAsync(); string jsonText = string.Empty; + // If the text is already JSON, return it + if (IsJson(text)) + { + return text; + } + // Try convert XML try {