Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 7ed93a8

Browse files
bremnesRupengLiu
authored andcommitted
[Extractor] Handle non-valid json as an operation sample without throwing an exception (#328)
* Handle non-valid json as an operation sample without throwing an exception. * Extractor: when checking if we need to arm escape the sample response we need to check if content type contains application/json, not equals since it can contain charset information and other things.
1 parent 597888f commit 7ed93a8

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/APIM_ARMTemplate/apimtemplate/Extractor/EntityExtractors/APIExtractor.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
24
using System.Threading.Tasks;
5+
using apimtemplate.Extractor.Utilities;
36
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
4-
using System.Collections.Generic;
5-
using Newtonsoft.Json.Linq;
67
using Newtonsoft.Json;
7-
using System.Linq;
8+
using Newtonsoft.Json.Linq;
89

910
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
1011
{
@@ -786,7 +787,7 @@ public async Task<Template> GenerateAPIsARMTemplateAsync(string apimname, string
786787

787788
private static void ArmEscapeSampleValueIfNecessary(OperationTemplateRepresentation operationTemplateRepresentation)
788789
{
789-
if (!string.IsNullOrWhiteSpace(operationTemplateRepresentation.sample) && operationTemplateRepresentation.contentType == "application/json" && JToken.Parse(operationTemplateRepresentation.sample).Type == JTokenType.Array)
790+
if (!string.IsNullOrWhiteSpace(operationTemplateRepresentation.sample) && operationTemplateRepresentation.contentType?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true && operationTemplateRepresentation.sample.TryParseJson(out JToken sampleAsJToken) && sampleAsJToken.Type == JTokenType.Array)
790791
{
791792
operationTemplateRepresentation.sample = "[" + operationTemplateRepresentation.sample;
792793
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
using Newtonsoft.Json.Linq;
3+
4+
namespace apimtemplate.Extractor.Utilities
5+
{
6+
static class StringExtensions
7+
{
8+
internal static bool TryParseJson(this string str, out JToken result)
9+
{
10+
try
11+
{
12+
result = JToken.Parse(str);
13+
return true;
14+
}
15+
catch (Exception)
16+
{
17+
18+
}
19+
20+
result = null;
21+
return false;
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)