This commit is contained in:
Stef Heyenrath
2026-04-26 18:59:33 +02:00
parent 64d3e4cbf3
commit 1e07f3f7f3
9 changed files with 36 additions and 69 deletions
@@ -25,7 +25,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Abstractions" Version="0.10.0" /> <PackageReference Include="JsonConverter.Abstractions" Version="0.11.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -1,10 +1,12 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Stef.Validation; using Stef.Validation;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Serialization;
using WireMock.Util; using WireMock.Util;
using JsonUtils = WireMock.Util.JsonUtils;
namespace WireMock.Matchers; namespace WireMock.Matchers;
@@ -68,7 +70,7 @@ public class JsonMatcher : IJsonMatcher
Regex = regex; Regex = regex;
Value = value; Value = value;
_valueAsJToken = JsonUtils.ConvertValueToJToken(value); _valueAsJToken = ConvertValueToJToken(value);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -82,7 +84,7 @@ public class JsonMatcher : IJsonMatcher
{ {
try try
{ {
var inputAsJToken = JsonUtils.ConvertValueToJToken(input); var inputAsJToken = ConvertValueToJToken(input);
var match = IsMatch(RenameJToken(_valueAsJToken), RenameJToken(inputAsJToken)); var match = IsMatch(RenameJToken(_valueAsJToken), RenameJToken(inputAsJToken));
score = MatchScores.ToScore(match); score = MatchScores.ToScore(match);
@@ -102,7 +104,7 @@ public class JsonMatcher : IJsonMatcher
return $"new {Name}" + return $"new {Name}" +
$"(" + $"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " + $"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{CSharpFormatter.ConvertToAnonymousObjectDefinition(Value, 3)}, " + $"{CSharpFormatter.ConvertToAnonymousObjectDefinition(Value, 3)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " + $"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(Regex)}" + $"{CSharpFormatter.ToCSharpBooleanLiteral(Regex)}" +
$")"; $")";
@@ -240,6 +242,18 @@ public class JsonMatcher : IJsonMatcher
return new JObject(renamedProperties); return new JObject(renamedProperties);
} }
private static JToken ConvertValueToJToken(object value)
{
// Check if JToken, string, IEnumerable or object
return value switch
{
JToken tokenValue => tokenValue,
string stringValue => JsonConvert.DeserializeObject<JToken>(stringValue, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone)!,
IEnumerable enumerableValue => JArray.FromObject(enumerableValue),
_ => JObject.FromObject(value),
};
}
private static string? ToUpper(string? input) private static string? ToUpper(string? input)
{ {
return input?.ToUpperInvariant(); return input?.ToUpperInvariant();
@@ -197,7 +197,7 @@ public partial class Response : IResponseBuilder
if (ProxyAndRecordSettings != null && _httpClientForProxy != null) if (ProxyAndRecordSettings != null && _httpClientForProxy != null)
{ {
string RemoveFirstOccurrence(string source, string find) static string RemoveFirstOccurrence(string source, string find)
{ {
int place = source.IndexOf(find, StringComparison.OrdinalIgnoreCase); int place = source.IndexOf(find, StringComparison.OrdinalIgnoreCase);
return place >= 0 ? source.Remove(place, find.Length) : source; return place >= 0 ? source.Remove(place, find.Length) : source;
@@ -265,7 +265,7 @@ public partial class Response : IResponseBuilder
var decoded = await protoBufMatcher.DecodeAsync(requestMessage.BodyData?.BodyAsBytes).ConfigureAwait(false); var decoded = await protoBufMatcher.DecodeAsync(requestMessage.BodyData?.BodyAsBytes).ConfigureAwait(false);
if (decoded != null) if (decoded != null)
{ {
requestMessageImplementation.BodyAsJson = JsonUtils.ConvertValueToJToken(decoded); requestMessageImplementation.BodyAsJson = settings.DefaultJsonSerializer.ToJsonToken(decoded);
} }
} }
} }
@@ -914,16 +914,16 @@ public partial class WireMockServer
}; };
} }
private static T DeserializeObject<T>(IRequestMessage requestMessage) private T DeserializeObject<T>(IRequestMessage requestMessage)
{ {
switch (requestMessage.BodyData?.DetectedBodyType) switch (requestMessage.BodyData?.DetectedBodyType)
{ {
case BodyType.String: case BodyType.String when requestMessage.BodyData?.BodyAsString != null:
case BodyType.FormUrlEncoded: case BodyType.FormUrlEncoded when requestMessage.BodyData?.BodyAsString != null:
return JsonUtils.DeserializeObject<T>(requestMessage.BodyData.BodyAsString!); return _settings.DefaultJsonSerializer.Deserialize<T>(requestMessage.BodyData.BodyAsString)!;
case BodyType.Json when requestMessage.BodyData?.BodyAsJson != null: case BodyType.Json when requestMessage.BodyData?.BodyAsJson != null:
return ((JObject)requestMessage.BodyData.BodyAsJson).ToObject<T>()!; return _settings.DefaultJsonSerializer.ParseJsonToken<T>(requestMessage.BodyData.BodyAsJson)!;
default: default:
throw new NotSupportedException(); throw new NotSupportedException();
@@ -1,6 +1,5 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System.Linq;
using Stef.Validation; using Stef.Validation;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Matchers; using WireMock.Matchers;
@@ -153,7 +152,7 @@ public partial class WireMockServer
} }
else else
{ {
var clientIPModel = JsonUtils.ParseJTokenToObject<ClientIPModel>(requestModel.ClientIP); var clientIPModel = _settings.DefaultJsonSerializer.ParseJsonToken<ClientIPModel>(requestModel.ClientIP);
if (clientIPModel.Matchers != null) if (clientIPModel.Matchers != null)
{ {
requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
@@ -169,7 +168,7 @@ public partial class WireMockServer
} }
else else
{ {
var pathModel = JsonUtils.ParseJTokenToObject<PathModel>(requestModel.Path); var pathModel = _settings.DefaultJsonSerializer.ParseJsonToken<PathModel>(requestModel.Path);
if (pathModel.Matchers != null) if (pathModel.Matchers != null)
{ {
var matchOperator = StringUtils.ParseMatchOperator(pathModel.MatchOperator); var matchOperator = StringUtils.ParseMatchOperator(pathModel.MatchOperator);
@@ -185,7 +184,7 @@ public partial class WireMockServer
} }
else else
{ {
var urlModel = JsonUtils.ParseJTokenToObject<UrlModel>(requestModel.Url); var urlModel = _settings.DefaultJsonSerializer.ParseJsonToken<UrlModel>(requestModel.Url);
if (urlModel.Matchers != null) if (urlModel.Matchers != null)
{ {
var matchOperator = StringUtils.ParseMatchOperator(urlModel.MatchOperator); var matchOperator = StringUtils.ParseMatchOperator(urlModel.MatchOperator);
@@ -271,7 +270,7 @@ public partial class WireMockServer
return requestBuilder; return requestBuilder;
} }
private static IResponseBuilder InitResponseBuilder(ResponseModel responseModel) private IResponseBuilder InitResponseBuilder(ResponseModel responseModel)
{ {
var responseBuilder = Response.Create(); var responseBuilder = Response.Create();
@@ -336,7 +335,7 @@ public partial class WireMockServer
} }
else else
{ {
var headers = JsonUtils.ParseJTokenToObject<string[]>(entry.Value); var headers = _settings.DefaultJsonSerializer.ParseJsonToken<string[]>(entry.Value);
responseBuilder.WithHeader(entry.Key, headers); responseBuilder.WithHeader(entry.Key, headers);
} }
} }
@@ -362,7 +361,7 @@ public partial class WireMockServer
} }
else else
{ {
var headers = JsonUtils.ParseJTokenToObject<string[]>(entry.Value); var headers = _settings.DefaultJsonSerializer.ParseJsonToken<string[]>(entry.Value);
responseBuilder.WithTrailingHeader(entry.Key, headers); responseBuilder.WithTrailingHeader(entry.Key, headers);
} }
} }
@@ -25,7 +25,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.10.0" /> <PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.11.0" />
<PackageReference Include="NUnit" Version="4.4.0" /> <PackageReference Include="NUnit" Version="4.4.0" />
<PackageReference Include="Stef.Validation" Version="0.2.0" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
</ItemGroup> </ItemGroup>
@@ -33,7 +33,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.10.0" /> <PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.11.0" />
<PackageReference Include="RestEase" Version="1.6.4" /> <PackageReference Include="RestEase" Version="1.6.4" />
<PackageReference Include="Stef.Validation" Version="0.2.0" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
</ItemGroup> </ItemGroup>
-46
View File
@@ -1,6 +1,5 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System.Collections;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text; using System.Text;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -50,17 +49,6 @@ internal static class JsonUtils
return Encoding.UTF8.GetBytes(json); return Encoding.UTF8.GetBytes(json);
} }
/// <summary>
/// Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON.
/// Using : DateParseHandling = DateParseHandling.None
/// </summary>
/// <param name="json">A System.String that contains JSON.</param>
/// <returns>A Newtonsoft.Json.Linq.JToken populated from the string that contains JSON.</returns>
public static JToken Parse(string json)
{
return JsonConvert.DeserializeObject<JToken>(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone)!;
}
/// <summary> /// <summary>
/// Deserializes the JSON to a .NET object. /// Deserializes the JSON to a .NET object.
/// Using : DateParseHandling = DateParseHandling.None /// Using : DateParseHandling = DateParseHandling.None
@@ -94,38 +82,4 @@ internal static class JsonUtils
return default; return default;
} }
} }
public static T ParseJTokenToObject<T>(object? value)
{
if (value != null && value.GetType() == typeof(T))
{
return (T)value;
}
return value switch
{
JToken tokenValue => tokenValue.ToObject<T>()!,
_ => throw new NotSupportedException($"Unable to convert value to {typeof(T)}.")
};
}
public static JToken ConvertValueToJToken(object value)
{
// Check if JToken, string, IEnumerable or object
switch (value)
{
case JToken tokenValue:
return tokenValue;
case string stringValue:
return Parse(stringValue);
case IEnumerable enumerableValue:
return JArray.FromObject(enumerableValue);
default:
return JObject.FromObject(value);
}
}
} }
@@ -30,8 +30,8 @@
<PackageReference Include="Stef.Validation" Version="0.2.0" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="AnyOf" Version="0.5.0.1" /> <PackageReference Include="AnyOf" Version="0.5.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.10.0" /> <PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.11.0" />
<PackageReference Include="JsonConverter.System.Text.Json" Version="0.10.0" /> <PackageReference Include="JsonConverter.System.Text.Json" Version="0.11.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>