Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class ResponseModel
public object? BodyAsJson { get; set; }

/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// Gets or sets a value indicating whether the Json Body String needs to be indented.
/// </summary>
public bool? BodyAsJsonIndented { get; set; }

Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net.Abstractions/Models/IBodyData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public interface IBodyData
object? BodyAsJson { get; set; }

/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// Gets or sets a value indicating whether the Json Body String needs to be indented.
/// </summary>
bool? BodyAsJsonIndented { get; set; }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>WireMock.Net.Routing extends WireMock.Net with modern, minimal-API-style routing for .NET</Description>
<Authors>Gennadii Saltyshchak</Authors>
Expand All @@ -25,7 +25,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" />
<PackageReference Include="JsonConverter.Abstractions" Version="0.8.0" />
</ItemGroup>

<ItemGroup>
Expand Down
5 changes: 2 additions & 3 deletions src/WireMock.Net.Minimal/MappingBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Stef.Validation;
using WireMock.Admin.Mappings;
using WireMock.Matchers.Request;
Expand Down Expand Up @@ -164,8 +163,8 @@ private void RegisterMapping(IMapping mapping, bool saveToFile)
}
}

private static string ToJson(object value)
private string ToJson(object value)
{
return JsonConvert.SerializeObject(value, JsonSerializationConstants.JsonSerializerSettingsDefault);
return _settings.DefaultJsonSerializer.Serialize(value, JsonSerializationConstants.JsonConverterOptionsDefault);
}
}
49 changes: 49 additions & 0 deletions src/WireMock.Net.Minimal/Serialization/MappingSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright © WireMock.Net

using System;
using JsonConverter.Abstractions;
using Newtonsoft.Json.Linq;
#if NETSTANDARD2_0_OR_GREATER || NETCOREAPP3_1_OR_GREATER || NET6_0_OR_GREATER || NET461
using System.Text.Json;
#endif

namespace WireMock.Serialization;

internal class MappingSerializer(IJsonConverter jsonConverter)
{
internal T[] DeserializeJsonToArray<T>(string value)
{
return DeserializeObjectToArray<T>(jsonConverter.Deserialize<object>(value)!);
}

internal static T[] DeserializeObjectToArray<T>(object value)
{
if (value is JArray jArray)
{
return jArray.ToObject<T[]>()!;
}

if (value is JObject jObject)
{
var singleResult = jObject.ToObject<T>();
return [singleResult!];
}

#if NETSTANDARD2_0_OR_GREATER || NETCOREAPP3_1_OR_GREATER || NET6_0_OR_GREATER || NET461
if (value is JsonElement jElement)
{
if (jElement.ValueKind == JsonValueKind.Array)
{
return jElement.Deserialize<T[]>()!;
}

if (jElement.ValueKind == JsonValueKind.Object)
{
var singleResult = jElement.Deserialize<T>();
return [singleResult!];
}
}
#endif
throw new InvalidOperationException("Cannot deserialize the provided value to an array or object.");
}
}
10 changes: 8 additions & 2 deletions src/WireMock.Net.Minimal/Serialization/MappingToFileSaver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

using System.IO;
using System.Linq;
using Newtonsoft.Json;
using JsonConverter.Abstractions;
using JsonConverter.Newtonsoft.Json;
using Stef.Validation;
using WireMock.Settings;

Expand All @@ -12,12 +13,15 @@ internal class MappingToFileSaver
{
private readonly WireMockServerSettings _settings;
private readonly MappingConverter _mappingConverter;
private readonly IJsonConverter _jsonConverter;
private readonly MappingFileNameSanitizer _fileNameSanitizer;

public MappingToFileSaver(WireMockServerSettings settings, MappingConverter mappingConverter)
{
_settings = Guard.NotNull(settings);
_mappingConverter = Guard.NotNull(mappingConverter);

_jsonConverter = settings.DefaultJsonSerializer ?? new NewtonsoftJsonConverter();
_fileNameSanitizer = new MappingFileNameSanitizer(settings);
}

Expand Down Expand Up @@ -56,6 +60,8 @@ private void Save(object value, string path)
{
_settings.Logger.Info("Saving Mapping file {0}", path);

_settings.FileSystemHandler.WriteMappingFile(path, JsonConvert.SerializeObject(value, JsonSerializationConstants.JsonSerializerSettingsDefault));
var json = _jsonConverter.Serialize(value, JsonSerializationConstants.JsonConverterOptionsDefault);

_settings.FileSystemHandler.WriteMappingFile(path, json);
}
}
62 changes: 26 additions & 36 deletions src/WireMock.Net.Minimal/Server/WireMockServer.Admin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using System.Net;
using System.Text;
using JetBrains.Annotations;
using Newtonsoft.Json;
using JsonConverter.Abstractions;
using Newtonsoft.Json.Linq;
using Stef.Validation;
using WireMock.Admin.Mappings;
Expand Down Expand Up @@ -236,7 +236,7 @@ public bool ReadStaticMappingAndAddOrUpdate(string path)

if (FileHelper.TryReadMappingFileWithRetryAndDelay(_settings.FileSystemHandler, path, out var value))
{
var mappingModels = DeserializeJsonToArray<MappingModel>(value);
var mappingModels = _mappingSerializer.DeserializeJsonToArray<MappingModel>(value);
if (mappingModels.Length == 1 && Guid.TryParse(filenameWithoutExtension, out var guidFromFilename))
{
ConvertMappingAndRegisterAsRespondProvider(mappingModels[0], guidFromFilename, path);
Expand Down Expand Up @@ -826,25 +826,31 @@ private void EnhancedFileSystemWatcherDeleted(object sender, FileSystemEventArgs
}
}

private static Encoding? ToEncoding(EncodingModel? encodingModel)
private ResponseMessage ToJson<T>(T result, bool keepNullValues = false, object? statusCode = null)
{
return encodingModel != null ? Encoding.GetEncoding(encodingModel.CodePage) : null;
}
var jsonOptions = new JsonConverterOptions
{
WriteIndented = true,
IgnoreNullValues = !keepNullValues
};

private static ResponseMessage ToJson<T>(T result, bool keepNullValues = false, object? statusCode = null)
{
return new ResponseMessage
{
BodyData = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = JsonConvert.SerializeObject(result, keepNullValues ? JsonSerializationConstants.JsonSerializerSettingsIncludeNullValues : JsonSerializationConstants.JsonSerializerSettingsDefault)
BodyAsString = _settings.DefaultJsonSerializer.Serialize(result!, jsonOptions)
},
StatusCode = statusCode ?? (int)HttpStatusCode.OK,
Headers = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string>(WireMockConstants.ContentTypeJson) } }
};
}

private static Encoding? ToEncoding(EncodingModel? encodingModel)
{
return encodingModel != null ? Encoding.GetEncoding(encodingModel.CodePage) : null;
}

private static ResponseMessage ToResponseMessage(string text)
{
return new ResponseMessage
Expand All @@ -859,6 +865,18 @@ private static ResponseMessage ToResponseMessage(string text)
};
}

private static T[] DeserializeRequestMessageToArray<T>(IRequestMessage requestMessage)
{
if (requestMessage.BodyData?.DetectedBodyType == BodyType.Json && requestMessage.BodyData.BodyAsJson != null)
{
var bodyAsJson = requestMessage.BodyData.BodyAsJson!;

return MappingSerializer.DeserializeObjectToArray<T>(bodyAsJson);
}

throw new NotSupportedException();
}

private static T DeserializeObject<T>(IRequestMessage requestMessage) where T : new()
{
switch (requestMessage.BodyData?.DetectedBodyType)
Expand All @@ -874,32 +892,4 @@ private static ResponseMessage ToResponseMessage(string text)
throw new NotSupportedException();
}
}

private static T[] DeserializeRequestMessageToArray<T>(IRequestMessage requestMessage)
{
if (requestMessage.BodyData?.DetectedBodyType == BodyType.Json && requestMessage.BodyData.BodyAsJson != null)
{
var bodyAsJson = requestMessage.BodyData.BodyAsJson;

return DeserializeObjectToArray<T>(bodyAsJson);
}

throw new NotSupportedException();
}

private static T[] DeserializeJsonToArray<T>(string value)
{
return DeserializeObjectToArray<T>(JsonUtils.DeserializeObject(value));
}

private static T[] DeserializeObjectToArray<T>(object value)
{
if (value is JArray jArray)
{
return jArray.ToObject<T[]>()!;
}

var singleResult = ((JObject)value).ToObject<T>();
return new[] { singleResult! };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void ReadStaticWireMockOrgMappingAndAddOrUpdate(string path)

if (FileHelper.TryReadMappingFileWithRetryAndDelay(_settings.FileSystemHandler, path, out var value))
{
var mappings = DeserializeJsonToArray<OrgMapping>(value);
var mappings = _mappingSerializer.DeserializeJsonToArray<OrgMapping>(value);
foreach (var mapping in mappings)
{
if (mappings.Length == 1 && Guid.TryParse(filenameWithoutExtension, out var guidFromFilename))
Expand Down
6 changes: 5 additions & 1 deletion src/WireMock.Net.Minimal/Server/WireMockServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Threading;
using AnyOfTypes;
using JetBrains.Annotations;
using JsonConverter.Newtonsoft.Json;
using Newtonsoft.Json;
using Stef.Validation;
using WireMock.Admin.Mappings;
Expand Down Expand Up @@ -47,6 +48,7 @@ public partial class WireMockServer : IWireMockServer
private readonly MappingBuilder _mappingBuilder;
private readonly IGuidUtils _guidUtils = new GuidUtils();
private readonly IDateTimeUtils _dateTimeUtils = new DateTimeUtils();
private readonly MappingSerializer _mappingSerializer;

/// <inheritdoc />
[PublicAPI]
Expand Down Expand Up @@ -357,6 +359,8 @@ protected WireMockServer(WireMockServerSettings settings)
{
_settings = Guard.NotNull(settings);

_mappingSerializer = new MappingSerializer(settings.DefaultJsonSerializer ?? new NewtonsoftJsonConverter());

// Set default values if not provided
_settings.Logger = settings.Logger ?? new WireMockNullLogger();
_settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler();
Expand Down Expand Up @@ -639,7 +643,7 @@ public IWireMockServer WithMapping(params MappingModel[] mappings)
[PublicAPI]
public IWireMockServer WithMapping(string mappings)
{
var mappingModels = DeserializeJsonToArray<MappingModel>(mappings);
var mappingModels = _mappingSerializer.DeserializeJsonToArray<MappingModel>(mappings);
foreach (var mappingModel in mappingModels)
{
ConvertMappingAndRegisterAsRespondProvider(mappingModel, mappingModel.Guid ?? Guid.NewGuid());
Expand Down
8 changes: 5 additions & 3 deletions src/WireMock.Net.Minimal/WireMock.Net.Minimal.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>Minimal version from the lightweight Http Mocking Server for .NET</Description>
<AssemblyTitle>WireMock.Net.Minimal</AssemblyTitle>
Expand Down Expand Up @@ -57,8 +57,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="JsonConverter.Abstractions" Version="0.7.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<!--<PackageReference Include="JsonConverter.Abstractions" Version="0.8.0" />-->
<!--<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.8.0" />-->
<PackageReference Include="NJsonSchema.Extensions" Version="0.1.0" />
<PackageReference Include="NSwag.Core" Version="13.16.1" />
<PackageReference Include="SimMetrics.Net" Version="1.0.5" />
Expand Down Expand Up @@ -118,11 +118,13 @@

<!-- https://github.com/wiremock/WireMock.Net/issues/507 -->
<PackageReference Include="Microsoft.AspNetCore.Server.IIS" Version="2.2.6" />
<PackageReference Include="JsonConverter.System.Text.Json" Version="0.8.0" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'">
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Scriban.Signed" Version="5.5.0" />
<PackageReference Include="JsonConverter.System.Text.Json" Version="0.8.0" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net.RestClient/WireMock.Net.RestClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" />
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.8.0" />
<PackageReference Include="RestEase" Version="1.6.4" />
<PackageReference Include="Stef.Validation" Version="0.1.1" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
// Copyright © WireMock.Net

using JsonConverter.Abstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace WireMock.Serialization;

internal static class JsonSerializationConstants
{
public static readonly JsonSerializerSettings JsonSerializerSettingsDefault = new()
internal static readonly JsonConverterOptions JsonConverterOptionsDefault = new()
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
WriteIndented = true,
IgnoreNullValues = true
};

public static readonly JsonSerializerSettings JsonSerializerSettingsIncludeNullValues = new()
//internal static readonly JsonSerializerSettings JsonSerializerSettingsDefault = new()
//{
// Formatting = Formatting.Indented,
// NullValueHandling = NullValueHandling.Ignore
//};

internal static readonly JsonSerializerSettings JsonSerializerSettingsIncludeNullValues = new()
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Include
};

public static readonly JsonSerializerSettings JsonDeserializerSettingsWithDateParsingNone = new()
internal static readonly JsonSerializerSettings JsonDeserializerSettingsWithDateParsingNone = new()
{
DateParseHandling = DateParseHandling.None
};

public static readonly JsonSerializerSettings JsonSerializerSettingsPact = new()
internal static readonly JsonSerializerSettings JsonSerializerSettingsPact = new()
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
Expand Down
Loading
Loading