Skip to content

Commit

Permalink
Replace JSON.NET with System.Text.Json (#207)
Browse files Browse the repository at this point in the history
Co-authored-by: Diogo Trindade <diogotr7@gmail.com>
  • Loading branch information
RobertBeekman and diogotr7 authored Feb 28, 2024
1 parent 1de253c commit 68f98c3
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 48 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Newtonsoft.Json;
using System.Text.Json.Serialization;
using Q42.HueApi;
using Q42.HueApi.Interfaces;
using Q42.HueApi.Models.Bridge;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Artemis.Core.Modules;
using Artemis.Core;
using Artemis.Core.Services;
using Artemis.Plugins.WebAPI.Json;
using EmbedIO;
using EmbedIO.Routing;
using EmbedIO.WebApi;
using Newtonsoft.Json;

namespace Artemis.Plugins.WebAPI.Controllers
{
internal class DataModelController : WebApiController
{
private readonly IDataModelService _dataModelService;
private readonly JsonSerializerSettings _serializerSettings;
private readonly JsonSerializerOptions _serializerSettings;

public DataModelController(IDataModelService dataModelService)
{
_dataModelService = dataModelService;
_serializerSettings = new JsonSerializerSettings {PreserveReferencesHandling = PreserveReferencesHandling.Objects, ContractResolver = new DataModelResolver()};
_serializerSettings = new JsonSerializerOptions(CoreJson.GetJsonSerializerOptions())
{
ReferenceHandler = ReferenceHandler.IgnoreCycles,
TypeInfoResolver = new DataModelJsonTypeInfoResolver()
};
}

[Route(HttpVerbs.Get, "/data-model")]
public async Task GetDataModel()
{
// Use a custom ContractResolver that respects [DataModelIgnore]
string json = JsonConvert.SerializeObject(_dataModelService.GetDataModels(), _serializerSettings);
// Cast to object to avoid the generic type being serialized
string json = JsonSerializer.Serialize(_dataModelService.GetDataModels().Cast<object>(), _serializerSettings);

HttpContext.Response.ContentType = MimeType.Json;
await using TextWriter writer = HttpContext.OpenResponseText();
Expand All @@ -38,12 +42,12 @@ public async Task GetDataModel()
[Route(HttpVerbs.Get, "/data-model/{plugin}")]
public async Task GetDataModel(Guid plugin)
{
DataModel dataModel = _dataModelService.GetDataModels().FirstOrDefault(dm => dm.Module.Plugin.Guid == plugin);
// Cast to object to avoid the generic type being serialized
object dataModel = _dataModelService.GetDataModels().FirstOrDefault(dm => dm.Module.Plugin.Guid == plugin);
if (dataModel == null)
throw HttpException.NotFound();

// Use a custom ContractResolver that respects [DataModelIgnore]
string json = JsonConvert.SerializeObject(dataModel, _serializerSettings);

string json = JsonSerializer.Serialize(dataModel, _serializerSettings);

HttpContext.Response.ContentType = MimeType.Json;
await using TextWriter writer = HttpContext.OpenResponseText();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Artemis.Core;
using Artemis.Core.Modules;

namespace Artemis.Plugins.WebAPI.Json;

public class DataModelJsonTypeInfoResolver : DefaultJsonTypeInfoResolver
{
public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options);

if (jsonTypeInfo.Kind == JsonTypeInfoKind.Object)
{
jsonTypeInfo.Properties.Clear();

foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetCustomAttribute<DataModelIgnoreAttribute>() != null)
continue;
if (propertyInfo.PropertyType.IsAssignableTo(typeof(IDataModelEvent)))
continue;

JsonPropertyInfo jsonPropertyInfo = jsonTypeInfo.CreateJsonPropertyInfo(propertyInfo.PropertyType, propertyInfo.Name);
jsonPropertyInfo.Get = propertyInfo.CanRead ? propertyInfo.GetValue : null;
jsonPropertyInfo.Set = propertyInfo.CanWrite ? (obj, value) => propertyInfo.SetValue(obj, value) : null;
jsonTypeInfo.Properties.Add(jsonPropertyInfo);
}
}

return jsonTypeInfo;
}
}
24 changes: 0 additions & 24 deletions src/Collections/Artemis.Plugins.WebAPI/Json/DataModelResolver.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@
<PackageReference Include="Humanizer.Core" Version="2.14.1" />
<PackageReference Include="JetBrains.Annotations" Version="2023.3.0" />
<PackageReference Include="McMaster.NETCore.Plugins" Version="1.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="RGB.NET.Core" Version="2.0.4-prerelease.16" />
<PackageReference Include="RGB.NET.Layout" Version="2.0.4-prerelease.16" />
<PackageReference Include="RGB.NET.Presets" Version="2.0.4-prerelease.16" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="SkiaSharp" Version="2.88.7" />
<PackageReference Include="System.Text.Json" Version="8.0.2" />

<!-- Artemis.UI.Shared -->
<PackageReference Include="Avalonia" Version="11.0.9" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Artemis.Core;
using Newtonsoft.Json;
using SkiaSharp;

namespace Artemis.Plugins.LayerBrushes.RemoteControl.Models
Expand All @@ -24,7 +24,6 @@ public RemoteControlBrushModel(RemoteControlBrush brush, bool includeLeds)
public Guid LayerId { get; set; }
public string LayerName { get; set; }

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<RemoteControlColorModel> LedColors { get; set; }
}

Expand Down
1 change: 0 additions & 1 deletion src/Modules/Artemis.Plugins.Modules.TestData/TestModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public override void Enable()
});
}


public override void Disable()
{
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Globalization;
using System.Text.Json;
using Artemis.Core;
using Avalonia.Data.Converters;
using Newtonsoft.Json;

namespace Artemis.Plugins.Nodes.General.Converters;

Expand All @@ -10,16 +10,24 @@ namespace Artemis.Plugins.Nodes.General.Converters;
/// </summary>
public class JsonConverter : IValueConverter
{
private readonly JsonSerializerOptions _options;

public JsonConverter()
{
_options = new JsonSerializerOptions(CoreJson.GetJsonSerializerOptions());
_options.WriteIndented = true;

}
/// <inheritdoc />
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return JsonConvert.SerializeObject(value, Formatting.Indented);
return JsonSerializer.Serialize(value, _options);
}

/// <inheritdoc />
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
string? json = value?.ToString();
return json == null ? null : JsonConvert.DeserializeObject(json, targetType);
return json == null ? null : JsonSerializer.Deserialize(json, targetType);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Artemis.Plugins.ScriptingProviders.JavaScript.EmbedIO;

Expand All @@ -18,7 +19,7 @@ public WebSocketCommand(string command, string argument)

public string Serialize()
{
return JsonConvert.SerializeObject(this);
return JsonSerializer.Serialize(this);
}

public string Command { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using Artemis.Plugins.ScriptingProviders.JavaScript.Generators;
using Artemis.Plugins.ScriptingProviders.JavaScript.Scripts;
using Artemis.Plugins.ScriptingProviders.JavaScript.Services;
using EmbedIO.WebSockets;
using Newtonsoft.Json;

namespace Artemis.Plugins.ScriptingProviders.JavaScript.EmbedIO;

Expand All @@ -25,8 +25,9 @@ protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[]
string content = Encoding.GetString(buffer);
try
{
WebSocketCommand command = JsonConvert.DeserializeObject<WebSocketCommand>(content);
OnWebSocketCommandReceived(new WebSocketCommandEventArgs(command));
WebSocketCommand? command = JsonSerializer.Deserialize<WebSocketCommand>(content);
if (command != null)
OnWebSocketCommandReceived(new WebSocketCommandEventArgs(command));
}
catch (Exception)
{
Expand Down

0 comments on commit 68f98c3

Please sign in to comment.