Skip to content

Commit

Permalink
Create custom converter for JSON serialization in .NET8 (#717)
Browse files Browse the repository at this point in the history
* Create custom converter for JSON serialization in .NET8

* Add check for different dictionary type for null replacement

---------

Co-authored-by: Eric Hua <[email protected]>
  • Loading branch information
ehua9146 and Eric Hua authored Apr 15, 2024
1 parent 7ded321 commit 5e7f6c6
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions Src/PChecker/CheckerCore/SystematicTesting/TestingEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,25 @@ public class TestingEngine
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
WriteIndented = true,
Converters = { new EncodingConverter() }
};

internal class EncodingConverter : JsonConverter<Encoding>
{
public override Encoding Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var name = reader.GetString();
if (name == null)
return null;
return Encoding.GetEncoding(name);
}
public override void Write(Utf8JsonWriter writer, Encoding value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.WebName);
}
}

/// <summary>
/// The profiler.
/// </summary>
Expand Down Expand Up @@ -618,9 +634,18 @@ public object RecursivelyReplaceNullWithString(object obj) {
if (obj == null) {
return "null";
}
if (obj is Dictionary<string, object> dictionary) {
if (obj is Dictionary<string, object> dictionaryStr) {
var newDictionary = new Dictionary<string, object>();
foreach (var item in dictionary) {
foreach (var item in dictionaryStr) {
var newVal = RecursivelyReplaceNullWithString(item.Value);
if (newVal != null)
newDictionary[item.Key] = newVal;
}
return newDictionary;
}
else if (obj is Dictionary<int, object> dictionaryInt) {
var newDictionary = new Dictionary<int, object>();
foreach (var item in dictionaryInt) {
var newVal = RecursivelyReplaceNullWithString(item.Value);
if (newVal != null)
newDictionary[item.Key] = newVal;
Expand Down

0 comments on commit 5e7f6c6

Please sign in to comment.