Skip to content

Commit 6bd8783

Browse files
daveMuellerDavid Mueller x
andauthored
Remove usage of System.Text.Json for now (#1637)
* started moving back to newtonsoft json * removed system text json * update change log * nit --------- Co-authored-by: David Mueller x <[email protected]>
1 parent 813f36c commit 6bd8783

File tree

8 files changed

+47
-83
lines changed

8 files changed

+47
-83
lines changed

Directory.Packages.props

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@
4444
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
4545
<PackageVersion Include="System.Linq.Async" Version="6.0.1" />
4646
<PackageVersion Include="System.Reflection.Metadata" Version="8.0.0" />
47-
<PackageVersion Include="System.Text.Json" Version="8.0.2" />
4847
<PackageVersion Include="Tmds.ExecFunction" Version="0.7.1" />
4948
<PackageVersion Include="xunit" Version="2.6.6" />
5049
<PackageVersion Include="xunit.assemblyfixture" Version="2.2.0" />

Documentation/Changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88

99
### Fixed
1010
- Threshold-stat triggers error [#1634](https://github.com/coverlet-coverage/coverlet/issues/1634)
11+
- Fixed coverlet collector 6.0.1 requires dotnet sdk 8 [#1625](https://github.com/coverlet-coverage/coverlet/issues/1625)
1112
- Exception when multiple exclude-by-attribute filters specified [#1624](https://github.com/coverlet-coverage/coverlet/issues/1624)
1213

1314
### Improvements

src/coverlet.core/Coverage.cs

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
using System.IO;
77
using System.Linq;
88
using System.Runtime.Serialization;
9-
using System.Text.Json;
10-
using System.Text.Json.Nodes;
9+
using Newtonsoft.Json;
10+
using Newtonsoft.Json.Linq;
1111
using Coverlet.Core.Abstractions;
1212
using Coverlet.Core.Helpers;
1313
using Coverlet.Core.Instrumentation;
@@ -60,14 +60,6 @@ internal class Coverage
6060

6161
public string Identifier { get; }
6262

63-
readonly JsonSerializerOptions _options = new()
64-
{
65-
PropertyNameCaseInsensitive = true,
66-
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
67-
IncludeFields = true,
68-
WriteIndented = true
69-
};
70-
7163
public Coverage(string moduleOrDirectory,
7264
CoverageParameters parameters,
7365
ILogger logger,
@@ -325,7 +317,7 @@ public CoverageResult GetCoverageResult()
325317
{
326318
_logger.LogInformation($"MergeWith: '{_parameters.MergeWith}'.");
327319
string json = _fileSystem.ReadAllText(_parameters.MergeWith);
328-
coverageResult.Merge(JsonSerializer.Deserialize<Modules>(json, _options));
320+
coverageResult.Merge(JsonConvert.DeserializeObject<Modules>(json));
329321
} else
330322
{
331323
_logger.LogInformation($"MergeWith: file '{_parameters.MergeWith}' does not exist.");
@@ -387,8 +379,8 @@ private void CalculateCoverage()
387379
var documents = result.Documents.Values.ToList();
388380
if (_parameters.UseSourceLink && result.SourceLink != null)
389381
{
390-
JsonNode jObject = JsonNode.Parse(result.SourceLink)["documents"];
391-
Dictionary<string, string> sourceLinkDocuments = JsonSerializer.Deserialize<Dictionary<string, string>>(jObject.ToString());
382+
JToken jObject = JObject.Parse(result.SourceLink)["documents"];
383+
Dictionary<string, string> sourceLinkDocuments = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObject.ToString());
392384
foreach (Document document in documents)
393385
{
394386
document.Path = GetSourceLinkUrl(sourceLinkDocuments, document.Path);

src/coverlet.core/CoverageResult.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
using System.Collections.Generic;
55
using System.Linq;
6-
using System.Text.Json.Serialization;
76
using Coverlet.Core.Enums;
87
using Coverlet.Core.Instrumentation;
98

@@ -23,11 +22,10 @@ internal class Branches : List<BranchInfo> { }
2322

2423
internal class Method
2524
{
26-
[JsonConstructor]
27-
public Method()
25+
internal Method()
2826
{
29-
Lines = [];
30-
Branches = [];
27+
Lines = new Lines();
28+
Branches = new Branches();
3129
}
3230

3331
public Lines Lines;

src/coverlet.core/Instrumentation/CecilAssemblyResolver.cs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
using System.Collections.Generic;
66
using System.IO;
77
using System.Linq;
8-
using System.Text.Json;
98
using Coverlet.Core.Abstractions;
109
using Coverlet.Core.Exceptions;
1110
using Microsoft.Extensions.DependencyModel;
1211
using Microsoft.Extensions.DependencyModel.Resolution;
1312
using Mono.Cecil;
13+
using Newtonsoft.Json.Linq;
1414
using NuGet.Versioning;
1515

1616
namespace Coverlet.Core.Instrumentation
@@ -298,25 +298,24 @@ public RuntimeConfigurationReader(string runtimeConfigFile)
298298
{
299299
string jsonString = File.ReadAllText(_runtimeConfigFile);
300300

301-
var documentOptions = new JsonDocumentOptions
301+
var jsonLoadSettings = new JsonLoadSettings()
302302
{
303-
CommentHandling = JsonCommentHandling.Skip
303+
CommentHandling = CommentHandling.Ignore
304304
};
305305

306-
using var configuration = JsonDocument.Parse(jsonString, documentOptions);
306+
var configuration = JObject.Parse(jsonString, jsonLoadSettings);
307307

308-
JsonElement rootElement = configuration.RootElement;
308+
JToken rootElement = configuration.Root;
309+
JToken runtimeOptionsElement = rootElement["runtimeOptions"];
309310

310-
JsonElement runtimeOptionsElement = rootElement.GetProperty("runtimeOptions");
311-
312-
if (runtimeOptionsElement.TryGetProperty("framework", out JsonElement frameworkElement))
311+
if (runtimeOptionsElement?["framework"] != null)
313312
{
314-
return new[] { (frameworkElement.GetProperty("name").GetString(), frameworkElement.GetProperty("version").GetString()) };
313+
return new[] { (runtimeOptionsElement["framework"]["name"]?.Value<string>(), runtimeOptionsElement["framework"]["version"]?.Value<string>()) };
315314
}
316315

317-
if (runtimeOptionsElement.TryGetProperty("frameworks", out JsonElement frameworksElement))
316+
if (runtimeOptionsElement?["frameworks"] != null)
318317
{
319-
return frameworksElement.EnumerateArray().Select(x => (x.GetProperty("name").GetString(), x.GetProperty("version").GetString())).ToList();
318+
return runtimeOptionsElement["frameworks"].Select(x => (x["name"]?.Value<string>(), x["version"]?.Value<string>())).ToList();
320319
}
321320

322321
throw new InvalidOperationException($"Unable to read runtime configuration from {_runtimeConfigFile}.");
Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
// Copyright (c) Toni Solarin-Sodara
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4-
using System.Text.Encodings.Web;
5-
using System.Text.Json;
64
using Coverlet.Core.Abstractions;
5+
using Newtonsoft.Json;
76

87
namespace Coverlet.Core.Reporters
98
{
@@ -17,13 +16,7 @@ internal class JsonReporter : IReporter
1716

1817
public string Report(CoverageResult result, ISourceRootTranslator _)
1918
{
20-
var options = new JsonSerializerOptions
21-
{
22-
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
23-
IncludeFields = true,
24-
WriteIndented = true,
25-
};
26-
return JsonSerializer.Serialize(result.Modules, options);
19+
return JsonConvert.SerializeObject(result.Modules, Formatting.Indented);
2720
}
2821
}
2922
}

src/coverlet.core/coverlet.core.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
<PackageReference Include="Microsoft.Extensions.DependencyInjection" VersionOverride="6.0.1"/>
1414
<PackageReference Include="Mono.Cecil" />
1515
<PackageReference Include="NuGet.Versioning" />
16-
<PackageReference Include="System.Text.Json" VersionOverride="6.0.9"/>
16+
<PackageReference Include="Newtonsoft.Json" />
1717
</ItemGroup>
1818

1919
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard2.0'">

test/coverlet.core.tests/Coverage/CoverageTests.cs

Lines changed: 25 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,23 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System;
5+
using System.Collections;
56
using System.Collections.Generic;
67
using System.IO;
78
using System.Linq;
8-
using System.Text.Encodings.Web;
9-
using System.Text.Json;
10-
using System.Text.Json.Serialization;
119
using Coverlet.Core.Abstractions;
1210
using Coverlet.Core.Helpers;
1311
using Coverlet.Core.Instrumentation;
1412
using Coverlet.Core.Symbols;
1513
using Moq;
14+
using Newtonsoft.Json;
1615
using Xunit;
1716

1817
namespace Coverlet.Core.Tests
1918
{
2019
public partial class CoverageTests
2120
{
2221
private readonly Mock<ILogger> _mockLogger = new();
23-
readonly JsonSerializerOptions _options = new()
24-
{
25-
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
26-
IncludeFields = true,
27-
WriteIndented = true,
28-
Converters =
29-
{
30-
new BranchDictionaryConverterFactory()
31-
}
32-
};
3322

3423
[Fact]
3524
public void TestCoverage()
@@ -102,7 +91,7 @@ public void TestCoverageWithTestAssembly()
10291
new SourceRootTranslator(module, _mockLogger.Object, new FileSystem(), new AssemblyAdapter()), new CecilSymbolHelper());
10392
coverage.PrepareModules();
10493

105-
string result = JsonSerializer.Serialize(coverage.GetCoverageResult(), _options);
94+
string result = JsonConvert.SerializeObject(coverage.GetCoverageResult(), Formatting.Indented, new BranchDictionaryConverter());
10695

10796
Assert.Contains("coverlet.core.tests.dll", result);
10897

@@ -141,7 +130,7 @@ public void TestCoverageMergeWithParameter()
141130
var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), parameters, _mockLogger.Object, instrumentationHelper, new FileSystem(), new SourceRootTranslator(_mockLogger.Object, new FileSystem()), new CecilSymbolHelper());
142131
coverage.PrepareModules();
143132

144-
string result = JsonSerializer.Serialize(coverage.GetCoverageResult(), _options);
133+
string result = JsonConvert.SerializeObject(coverage.GetCoverageResult(), Formatting.Indented, new BranchDictionaryConverter());
145134

146135
Assert.Contains("DeepThought.cs", result);
147136

@@ -182,51 +171,44 @@ public void TestCoverageMergeWithWrongParameter()
182171
var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), parameters, _mockLogger.Object, instrumentationHelper, new FileSystem(), new SourceRootTranslator(_mockLogger.Object, new FileSystem()), new CecilSymbolHelper());
183172
coverage.PrepareModules();
184173

185-
string result = JsonSerializer.Serialize(coverage.GetCoverageResult(), _options);
174+
JsonConvert.SerializeObject(coverage.GetCoverageResult());
186175

187176
_mockLogger.Verify(l => l.LogInformation(It.Is<string>(v => v.Equals("MergeWith: file 'FileDoesNotExist.json' does not exist.")), It.IsAny<bool>()), Times.Once);
188177

189178
directory.Delete(true);
190179
}
191180
}
192181
}
193-
public class BranchDictionaryConverterFactory : JsonConverterFactory
194-
{
195-
public override bool CanConvert(Type typeToConvert)
196-
{
197-
return typeof(Dictionary<BranchKey, Branch>).IsAssignableFrom(typeToConvert);
198-
}
199182

200-
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
183+
public class BranchDictionaryConverter: JsonConverter
184+
{
185+
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
201186
{
202-
Type[] genericArgs = typeToConvert.GetGenericArguments();
203-
Type keyType = genericArgs[0];
204-
Type valueType = genericArgs[1];
187+
Type type = value.GetType();
188+
var keys = (IEnumerable)type.GetProperty("Keys")?.GetValue(value, null);
189+
var values = (IEnumerable)type.GetProperty("Values")?.GetValue(value, null);
190+
IEnumerator valueEnumerator = values.GetEnumerator();
205191

206-
JsonConverter converter = (JsonConverter)Activator.CreateInstance(
207-
typeof(BranchDictionaryConverter<,>).MakeGenericType(new Type[] { keyType, valueType }));
192+
writer.WriteStartArray();
193+
foreach (object key in keys)
194+
{
195+
valueEnumerator.MoveNext();
208196

209-
return converter;
197+
writer.WriteStartArray();
198+
serializer.Serialize(writer, key);
199+
serializer.Serialize(writer, valueEnumerator.Current);
200+
writer.WriteEndArray();
201+
}
202+
writer.WriteEndArray();
210203
}
211-
}
212204

213-
public class BranchDictionaryConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
214-
{
215-
public override Dictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
205+
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
216206
{
217207
throw new NotImplementedException();
218208
}
219209

220-
public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializerOptions options)
210+
public override bool CanConvert(Type objectType)
221211
{
222-
writer.WriteStartObject();
223-
224-
foreach (KeyValuePair<TKey, TValue> pair in value)
225-
{
226-
writer.WritePropertyName(pair.Key.ToString());
227-
JsonSerializer.Serialize(writer, pair.Value, options);
228-
}
229-
230-
writer.WriteEndObject();
212+
return typeof(Dictionary<BranchKey, Branch>).IsAssignableFrom(objectType);
231213
}
232214
}

0 commit comments

Comments
 (0)