Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to System.Text.Json #21

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion .github/workflows/check_updates.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- uses: denoland/setup-deno@v1
- uses: actions/setup-dotnet@v1
with:
dotnet-version: "7.0.x"
dotnet-version: "8.0.x"

- name: Run script
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- uses: denoland/setup-deno@v1
- uses: actions/setup-dotnet@v1
with:
dotnet-version: "7.0.x"
dotnet-version: "8.0.x"

- name: Build (Debug)
run: dotnet build DprintPluginRoslyn
Expand All @@ -42,7 +42,7 @@ jobs:

- name: Package
run: |
RELEASE_DIR=$GITHUB_WORKSPACE/DprintPluginRoslyn/bin/Release/net7.0
RELEASE_DIR=$GITHUB_WORKSPACE/DprintPluginRoslyn/bin/Release/net8.0
# cd to each output directory so we only include its files
cd $RELEASE_DIR/osx-x64
zip -r ../../../../../dprint-plugin-roslyn-x86_64-apple-darwin.zip ./*
Expand Down
2 changes: 1 addition & 1 deletion DprintPluginRoslyn.Tests/DprintPluginRoslyn.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>

<IsPackable>false</IsPackable>

Expand Down
3 changes: 1 addition & 2 deletions DprintPluginRoslyn/DprintPluginRoslyn.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Dprint.Plugins.Roslyn</RootNamespace>
<AssemblyName>dprint-plugin-roslyn</AssemblyName>
<Nullable>enable</Nullable>
Expand All @@ -18,7 +18,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.8.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="4.8.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

</Project>
47 changes: 37 additions & 10 deletions DprintPluginRoslyn/Serialization/JsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,59 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Text;
using System;

namespace Dprint.Plugins.Roslyn.Serialization;

using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

public class JsonSerializer
{
public T Deserialize<T>(byte[] jsonData)
{
var jsonText = Encoding.UTF8.GetString(jsonData);
return JsonConvert.DeserializeObject<T>(jsonText, GetSettings()) ?? throw new Exception("Error deserializing JSON.");
return System.Text.Json.JsonSerializer.Deserialize<T>(jsonText, GetSettings()) ?? throw new Exception("Error deserializing JSON.");
}

public byte[] Serialize<T>(T obj)
{
var jsonText = JsonConvert.SerializeObject(obj, GetSettings()) ?? throw new Exception("Error serializing to JSON.");
var jsonText = System.Text.Json.JsonSerializer.Serialize(obj, GetSettings()) ?? throw new Exception("Error serializing to JSON.");
return Encoding.UTF8.GetBytes(jsonText);
}

private JsonSerializerSettings GetSettings()
private JsonSerializerOptions GetSettings()
{
return new JsonSerializerSettings
return new JsonSerializerOptions
{
ContractResolver = new DefaultContractResolver
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters =
{
NamingStrategy = new CamelCaseNamingStrategy()
new ObjectToInferredTypesConverter(),
}
};
}

// Match Newtonsoft Behaviour
// https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-8-0#deserialization-of-object-properties
private class ObjectToInferredTypesConverter : JsonConverter<object>
{
public override object Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) => reader.TokenType switch
{
JsonTokenType.True => true,
JsonTokenType.False => false,
JsonTokenType.Number when reader.TryGetInt64(out long l) => l,
JsonTokenType.Number => reader.GetDouble(),
JsonTokenType.String when reader.TryGetDateTime(out DateTime datetime) => datetime,
JsonTokenType.String => reader.GetString()!,
_ => JsonDocument.ParseValue(ref reader).RootElement.Clone()
};

public override void Write(
Utf8JsonWriter writer,
object objectToWrite,
JsonSerializerOptions options) =>
System.Text.Json.JsonSerializer.Serialize(writer, objectToWrite, objectToWrite.GetType(), options);
}
}
2 changes: 1 addition & 1 deletion test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ mod test {

async fn new_communicator() -> ProcessPluginCommunicator {
let exe_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../DprintPluginRoslyn/bin/Debug/net7.0/")
.join("../DprintPluginRoslyn/bin/Debug/net8.0/")
.join(if cfg!(windows) { "dprint-plugin-roslyn.exe" } else { "dprint-plugin-roslyn" });
ProcessPluginCommunicator::new(&exe_path, |err| eprintln!("{}", err)).await.unwrap()
}
Expand Down
Loading