From 94867321bb6946b7149cad3f1a4f230e49f5e12e Mon Sep 17 00:00:00 2001 From: rabdulatif Date: Sun, 6 Oct 2024 18:15:52 +0500 Subject: [PATCH] Added TryParse method to parse json safely --- .../Extensions/JsonExtensions.cs | 30 +++++++++++++++++++ .../SwaggerJsonTransformer.Consul.cs | 5 +++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/MMLib.SwaggerForOcelot/Extensions/JsonExtensions.cs diff --git a/src/MMLib.SwaggerForOcelot/Extensions/JsonExtensions.cs b/src/MMLib.SwaggerForOcelot/Extensions/JsonExtensions.cs new file mode 100644 index 0000000..f56c288 --- /dev/null +++ b/src/MMLib.SwaggerForOcelot/Extensions/JsonExtensions.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json.Linq; +using System; + +namespace MMLib.SwaggerForOcelot.Extensions; + +/// +/// +/// +public static class JsonExtensions +{ + /// + /// + /// + /// + /// + /// + public static bool TryParse(this string swaggerJson, out JObject jObj) + { + try + { + jObj = JObject.Parse(swaggerJson); + return true; + } + catch (Exception ex) + { + jObj = null; + return false; + } + } +} diff --git a/src/MMLib.SwaggerForOcelot/Transformation/SwaggerJsonTransformer.Consul.cs b/src/MMLib.SwaggerForOcelot/Transformation/SwaggerJsonTransformer.Consul.cs index f0d6b2a..d7533ba 100644 --- a/src/MMLib.SwaggerForOcelot/Transformation/SwaggerJsonTransformer.Consul.cs +++ b/src/MMLib.SwaggerForOcelot/Transformation/SwaggerJsonTransformer.Consul.cs @@ -1,4 +1,5 @@ using MMLib.SwaggerForOcelot.Configuration; +using MMLib.SwaggerForOcelot.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; @@ -33,7 +34,9 @@ public string AddServiceNamePrefixToPaths(string swaggerJson, SwaggerEndPointOpt if (string.IsNullOrEmpty(serviceName)) return swaggerJson; - var swaggerObj = JObject.Parse(swaggerJson); + if (!swaggerJson.TryParse(out var swaggerObj)) + return swaggerJson; + if (!swaggerObj.TryGetValue(OpenApiProperties.Paths, out var swaggerPaths)) return swaggerJson;