Skip to content

Instantly share code, notes, and snippets.

@manne
Last active January 12, 2020 23:14
Show Gist options
  • Save manne/ce7506772a71dcb91c768c37295e9d4c to your computer and use it in GitHub Desktop.
Save manne/ce7506772a71dcb91c768c37295e9d4c to your computer and use it in GitHub Desktop.
Support immutable types for System.Text.Json
MIT License
Copyright (c) 2020 Manuel Pfemeter
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<Query Kind="Program">
<NuGetReference>System.Collections.Immutable</NuGetReference>
<NuGetReference>System.Memory</NuGetReference>
<NuGetReference>System.Text.Json</NuGetReference>
<Namespace>System.Collections.Immutable</Namespace>
<Namespace>System.Text.Json</Namespace>
<Namespace>System.Text.Json.Serialization</Namespace>
<Namespace>System.Globalization</Namespace>
</Query>
void Main()
{
const string value1 = @"{""Bar"": [""aa"", ""bb""]}";
Run<FooOneProperty>(value1).Dump("1");
const string value2 = @"{""Bar"": [""aa"", ""bb""], ""Cool"": ""EventCooler""}";
Run<FooTwoProperties>(value2).Dump("2");
const string value3 = @"{""Bar"": [""aa"", ""bb""], ""Cool"": ""EventCooler""}";
Run<FooTwo2Properties>(value3).Dump("3");
const string value4 = @"{""Cool"": ""EventCooler"", ""Bar"": [""aa"", ""bb""]}";
Run<FooTwo2Properties>(value4).Dump("4");
const string value5 = @"{""NotThere1"": ""anyway"", ""Cool"": ""EventCooler"", ""Bar"": [""aa"", ""bb""], ""NotThere"": ""anyway""}";
Run<FooTwo2Properties>(value5).Dump("5");
const string value6 = @"{""NotThere1"": ""anyway"", ""Cool"": ""EventCooler"", ""NotThere3"": ""anyway3"", ""Bar"": [""aa"", ""bb""], ""NotThere"": ""anyway""}";
Run<FooTwo2Properties>(value6).Dump("6");
const string value7 = @"{""Thing"": [""aa"", ""bb""], ""Cool"": ""EventCooler""}";
Run<FooWithAttributeProperties>(value7).Dump("7");
}
static T Run<T>(string content)
{
var opt = new JsonSerializerOptions();
opt.Converters.Add(new ImmutableConverter());
return JsonSerializer.Deserialize<T>(content, opt);
}
public class FooOneProperty
{
public FooOneProperty(IImmutableList<string> bar)
{
Bar = bar;
}
public IImmutableList<string> Bar {get;}
}
public class FooTwoProperties
{
public FooTwoProperties(IImmutableList<string> bar, string cool)
{
Bar = bar;
Cool = cool;
}
public IImmutableList<string> Bar { get; }
public string Cool { get; }
}
public class FooTwo2Properties
{
public FooTwo2Properties(string cool, IImmutableList<string> bar)
{
Bar = bar;
Cool = cool;
}
public IImmutableList<string> Bar { get; }
public string Cool { get; }
}
public class FooWithAttributeProperties
{
public FooWithAttributeProperties(string cool, IImmutableList<string> bar)
{
Bar = bar;
Cool = cool;
}
[JsonPropertyName("Thing")]
public IImmutableList<string> Bar { get; }
public string Cool { get; }
}
public class ImmutableConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
return Helper.CanConvert(typeToConvert);
}
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dictionary = new Dictionary<PropertyInfo, object>();
var properties = Helper.GetNamedProperties(typeToConvert, options);
var s = reader.Read();
while (true)
{
if (reader.TokenType != JsonTokenType.PropertyName && reader.TokenType != JsonTokenType.String)
{
break;
}
var jsonPropName = reader.GetString();
if (!properties.TryGetValue(jsonPropName, out var obProp))
{
reader.Read();
continue;
}
else
{
var value = JsonSerializer.Deserialize(ref reader, obProp.PropertyType, options);
reader.Read();
dictionary[obProp] = value;
}
}
var ctor = typeToConvert.GetConstructors(BindingFlags.Public | BindingFlags.Instance).First();
var parameters = ctor.GetParameters();
var parameterValues = new object[parameters.Length];
for (var index = 0; index < parameters.Length; index++)
{
var parameterInfo = parameters[index];
var value = dictionary.First(prop =>
NameOfParameterAndPropertyEqualityComparer.Instance.Equals(prop.Key.Name, parameterInfo.Name)).Value;
parameterValues[index] = value;
}
var instance = ctor.Invoke(parameterValues);
return instance;
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new NotSupportedException();
}
}
public class NameOfParameterAndPropertyEqualityComparer : IEqualityComparer<string>
{
public static NameOfParameterAndPropertyEqualityComparer Instance { get; } = new NameOfParameterAndPropertyEqualityComparer();
private NameOfParameterAndPropertyEqualityComparer() {}
public bool Equals(string x, string y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
var xRight = x.AsSpan(1);
var yRight = y.AsSpan(1);
return x.ToLower(CultureInfo.InvariantCulture) == y && xRight.Equals(yRight, StringComparison.Ordinal);
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
public static class Helper
{
public static IImmutableDictionary<string, PropertyInfo> GetNamedProperties(Type typeToConvert, JsonSerializerOptions options)
{
var result = new Dictionary<string, PropertyInfo>();
void Add(PropertyInfo prop, string name)
{
if (!result.TryAdd(name, prop))
{
throw new InvalidOperationException();
}
}
var properties = typeToConvert.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var nameAttribute = property.GetCustomAttribute<JsonPropertyNameAttribute>();
if (nameAttribute != null)
{
Add(property, nameAttribute.Name);
}
else
{
Add(property, options.PropertyNamingPolicy?.ConvertName(property.Name) ?? property.Name);
}
}
return ImmutableDictionary.CreateRange(result);
}
public static bool PropertyEqualizer(this JsonSerializerOptions options, string jsonPropertyName, string other)
{
StringComparer comparer;
string convertedName;
comparer = options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
if (options.PropertyNamingPolicy == null)
{
convertedName = other;
}
else
{
convertedName = options.PropertyNamingPolicy.ConvertName(other);
}
return comparer.Compare(jsonPropertyName, convertedName) == 0;
}
public static bool CanConvert(Type typeToConvert)
{
bool IsSystem(Type t)
{
if (t.Namespace == null)
{
return false;
}
return t.Namespace.Equals("System", StringComparison.Ordinal) || t.Namespace.StartsWith("System.");
}
if (typeToConvert.IsPrimitive || IsSystem(typeToConvert))
{
return false;
}
if (typeToConvert.IsArray && (typeToConvert.GetElementType().IsPrimitive || IsSystem(typeToConvert)))
{
return false;
}
return typeToConvert.GetConstructors().Any(c => c.GetParameters().Length > 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment