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

Implement more conversions from JsonDynamicValue #15816

Merged
merged 16 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,8 @@ public class JsonDynamicArray : DynamicObject, IEnumerable<JsonNode?>

public object? this[int index]
{
get
{
var value = GetValue(index);
if (value is JsonDynamicValue jsonDynamicValue)
{
return jsonDynamicValue.JsonValue;
}

return value;
}
set
{
SetValue(index, value);
}
get => GetValue(index);
set => SetValue(index, value);
}

public bool Remove(JsonNode? item)
Expand All @@ -57,14 +45,7 @@ public void RemoveAt(int index)

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object? result)
{
var value = GetValue((int)indexes[0]);
if (value is JsonDynamicValue jsonDynamicValue)
{
result = jsonDynamicValue.Value;
return true;
}

result = value;
result = GetValue((int)indexes[0]);
return true;
}

Expand Down Expand Up @@ -116,7 +97,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object?[]? args,
return null;
}

public void SetValue(int index, object? value, object? nodeValue = null)
public void SetValue(int index, object? value)
{
if (value is null)
{
Expand All @@ -127,8 +108,7 @@ public void SetValue(int index, object? value, object? nodeValue = null)

if (value is not JsonNode)
{
var jsonNode = JNode.FromObject(value);
SetValue(index, jsonNode, value);
value = JNode.FromObject(value);
}

if (value is JsonObject jsonObject)
Expand All @@ -148,7 +128,7 @@ public void SetValue(int index, object? value, object? nodeValue = null)
if (value is JsonValue jsonValue)
{
_jsonArray[index] = jsonValue;
_dictionary[index] = new JsonDynamicValue(jsonValue, nodeValue);
_dictionary[index] = new JsonDynamicValue(jsonValue);
return;
}
}
Expand Down Expand Up @@ -183,14 +163,7 @@ public override bool TryGetMember(GetMemberBinder binder, out object? result)
return false;
}

var value = GetValue(index);
if (value is JsonDynamicValue jsonDynamicValue)
{
result = jsonDynamicValue.Value;
return true;
}

result = value;
result = GetValue(index);
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,8 @@ public class JsonDynamicObject : DynamicObject

public object? this[string key]
{
get
{
var value = GetValue(key);
if (value is JsonDynamicValue jsonDynamicValue)
{
return jsonDynamicValue.JsonValue;
}

return value;
}
set
{
SetValue(key, value);
}
get => GetValue(key);
set => SetValue(key, value);
}

public override bool TryGetMember(GetMemberBinder binder, out object? result)
Expand All @@ -57,14 +45,7 @@ public override bool TryGetMember(GetMemberBinder binder, out object? result)
return true;
}

var value = GetValue(binder.Name);
if (value is JsonDynamicValue jsonDynamicValue)
{
result = jsonDynamicValue.Value;
return true;
}

result = value;
result = GetValue(binder.Name);
return true;
}

Expand Down Expand Up @@ -127,7 +108,7 @@ public bool Remove(string key)
return null;
}

public void SetValue(string key, object? value, object? nodeValue = null)
public void SetValue(string key, object? value)
{
if (value is null)
{
Expand All @@ -138,8 +119,7 @@ public void SetValue(string key, object? value, object? nodeValue = null)

if (value is not JsonNode)
{
var jsonNode = JNode.FromObject(value);
SetValue(key, jsonNode, value);
value = JNode.FromObject(value);
}

if (value is JsonObject jsonObject)
Expand All @@ -159,7 +139,7 @@ public void SetValue(string key, object? value, object? nodeValue = null)
if (value is JsonValue jsonValue)
{
_jsonObject[key] = jsonValue;
_dictionary[key] = new JsonDynamicValue(jsonValue, nodeValue);
_dictionary[key] = new JsonDynamicValue(jsonValue);
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,155 @@
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json.Nodes;

namespace System.Text.Json.Dynamic;

#nullable enable

public class JsonDynamicValue
public class JsonDynamicValue : DynamicObject, IConvertible
{
private object? _value;
private bool _hasValue;

public JsonDynamicValue(JsonValue? jsonValue) => JsonValue = jsonValue;

public JsonDynamicValue(JsonValue? jsonValue, object? value)
public JsonValue? JsonValue { get; }

public override DynamicMetaObject GetMetaObject(Expression parameter)
{
JsonValue = jsonValue;
_value = value;
return new JsonDynamicMetaObject(parameter, this);
}

public JsonValue? JsonValue { get; }
public override string ToString() => JsonValue?.ToString() ?? string.Empty;

public object? Value
TypeCode IConvertible.GetTypeCode()
{
get
if (JsonValue == null)
{
if (!_hasValue)
return TypeCode.Empty;
}
return TypeCode.Object;
}

bool IConvertible.ToBoolean(IFormatProvider? provider) => (bool)this;
byte IConvertible.ToByte(IFormatProvider? provider) => (byte)this;
char IConvertible.ToChar(IFormatProvider? provider) => (char)this;
DateTime IConvertible.ToDateTime(IFormatProvider? provider) => (DateTime)this;
decimal IConvertible.ToDecimal(IFormatProvider? provider) => (decimal)this;
double IConvertible.ToDouble(IFormatProvider? provider) => (double)this;
short IConvertible.ToInt16(IFormatProvider? provider) => (short)this;
int IConvertible.ToInt32(IFormatProvider? provider) => (int)this;
long IConvertible.ToInt64(IFormatProvider? provider) => (long)this;
sbyte IConvertible.ToSByte(IFormatProvider? provider) => (sbyte)this;
float IConvertible.ToSingle(IFormatProvider? provider) => (float)this;
string IConvertible.ToString(IFormatProvider? provider) => (string?)this ?? string.Empty;
object IConvertible.ToType(Type conversionType, IFormatProvider? provider) => JsonValue?.ToObject(conversionType) ?? throw new InvalidOperationException($"Can not convert {this} to {conversionType}");
ushort IConvertible.ToUInt16(IFormatProvider? provider) => (ushort)this;
uint IConvertible.ToUInt32(IFormatProvider? provider) => (uint)this;
ulong IConvertible.ToUInt64(IFormatProvider? provider) => (ulong)this;

public static explicit operator bool(JsonDynamicValue value) => value?.JsonValue?.GetValue<bool>() ?? throw new InvalidCastException($"Can not convert {value} to Boolean");
public static explicit operator bool?(JsonDynamicValue value) => value?.JsonValue?.GetValue<bool?>();

public static explicit operator byte(JsonDynamicValue value) => value?.JsonValue?.GetValue<byte>() ?? throw new InvalidCastException($"Can not convert {value} to Byte");
public static explicit operator byte?(JsonDynamicValue value) => value?.JsonValue?.GetValue<byte?>();

public static explicit operator char(JsonDynamicValue value) => value?.JsonValue?.GetValue<char>() ?? throw new InvalidCastException($"Can not convert {value} to Char");
public static explicit operator char?(JsonDynamicValue value) => value?.JsonValue?.GetValue<char?>();

public static explicit operator DateTime(JsonDynamicValue value) => value?.JsonValue?.GetValue<DateTime>() ?? throw new InvalidCastException($"Can not convert {value} to DateTime");
public static explicit operator DateTime?(JsonDynamicValue value) => value?.JsonValue?.GetValue<DateTime?>();

public static explicit operator DateTimeOffset(JsonDynamicValue value) => value?.JsonValue?.GetValue<DateTimeOffset>() ?? throw new InvalidCastException($"Can not convert {value} to DateTimeOffset");
public static explicit operator DateTimeOffset?(JsonDynamicValue value) => value?.JsonValue?.GetValue<DateTimeOffset?>();

public static explicit operator decimal(JsonDynamicValue value) => value?.JsonValue?.GetValue<decimal>() ?? throw new InvalidCastException($"Can not convert {value} to Decimal");
public static explicit operator decimal?(JsonDynamicValue value) => value?.JsonValue?.GetValue<decimal?>();

public static explicit operator double(JsonDynamicValue value) => value?.JsonValue?.GetValue<double>() ?? throw new InvalidCastException($"Can not convert {value} to Double");
public static explicit operator double?(JsonDynamicValue value) => value?.JsonValue?.GetValue<double?>();

public static explicit operator Guid(JsonDynamicValue value) => value?.JsonValue?.GetValue<Guid>() ?? throw new InvalidCastException($"Can not convert {value} to Guid");
public static explicit operator Guid?(JsonDynamicValue value) => value?.JsonValue?.GetValue<Guid?>();

public static explicit operator short(JsonDynamicValue value) => value?.JsonValue?.GetValue<short>() ?? throw new InvalidCastException($"Can not convert {value} to Int16");
public static explicit operator short?(JsonDynamicValue value) => value?.JsonValue?.GetValue<short?>();

public static explicit operator int(JsonDynamicValue value) => value?.JsonValue?.GetValue<int>() ?? throw new InvalidCastException($"Can not convert {value} to Int32");
public static explicit operator int?(JsonDynamicValue value) => value?.JsonValue?.GetValue<int?>();

public static explicit operator long(JsonDynamicValue value) => value?.JsonValue?.GetValue<long>() ?? throw new InvalidCastException($"Can not convert {value} to Int64");
public static explicit operator long?(JsonDynamicValue value) => value?.JsonValue?.GetValue<long?>();

public static explicit operator sbyte(JsonDynamicValue value) => value?.JsonValue?.GetValue<sbyte>() ?? throw new InvalidCastException($"Can not convert {value} to SByte");
public static explicit operator sbyte?(JsonDynamicValue value) => value?.JsonValue?.GetValue<sbyte?>();

public static explicit operator float(JsonDynamicValue value) => value?.JsonValue?.GetValue<float>() ?? throw new InvalidCastException($"Can not convert {value} to Single");
public static explicit operator float?(JsonDynamicValue value) => value?.JsonValue?.GetValue<float?>();

public static explicit operator string?(JsonDynamicValue value) => value?.JsonValue?.GetValue<string>();

public static explicit operator ushort(JsonDynamicValue value) => value?.JsonValue?.GetValue<ushort>() ?? throw new InvalidCastException($"Can not convert {value} to UInt32");
public static explicit operator ushort?(JsonDynamicValue value) => value?.JsonValue?.GetValue<ushort?>();

public static explicit operator uint(JsonDynamicValue value) => value?.JsonValue?.GetValue<uint>() ?? throw new InvalidCastException($"Can not convert {value} to UInt32");
public static explicit operator uint?(JsonDynamicValue value) => value?.JsonValue?.GetValue<uint?>();

public static explicit operator ulong(JsonDynamicValue value) => value?.JsonValue?.GetValue<ulong>() ?? throw new InvalidCastException($"Can not convert {value} to UInt64");
public static explicit operator ulong?(JsonDynamicValue value) => value?.JsonValue?.GetValue<ulong?>();

public static explicit operator byte[]?(JsonDynamicValue value)
{
if (value?.JsonValue.GetObjectValue() is string str)
{
return Convert.FromBase64String(str);
}

throw new InvalidCastException($"Can not convert {value} to Byte array");
}

public static explicit operator TimeSpan(JsonDynamicValue value)
{
if(value?.JsonValue?.GetObjectValue() is string str)
{
return TimeSpan.Parse(str, CultureInfo.InvariantCulture);
}

throw new InvalidCastException($"Can not convert {value} to TimeSpan");
}

public static explicit operator TimeSpan?(JsonDynamicValue value)
{
var str = value?.JsonValue?.GetObjectValue() as string;

return str is null ? null : TimeSpan.Parse(str, CultureInfo.InvariantCulture);
}

public static explicit operator Uri?(JsonDynamicValue value) => new Uri(value?.JsonValue?.GetValue<string>() ?? string.Empty);

private sealed class JsonDynamicMetaObject : DynamicMetaObject
{
public JsonDynamicMetaObject(Expression expression, JsonDynamicValue value)
: base(expression, BindingRestrictions.Empty, value)
{
}

public override DynamicMetaObject BindConvert(ConvertBinder binder)
MikeAlhayek marked this conversation as resolved.
Show resolved Hide resolved
{
var targetType = binder.Type;

var castMethod = typeof(JsonDynamicValue).GetMethods(BindingFlags.Public | BindingFlags.Static)
MikeAlhayek marked this conversation as resolved.
Show resolved Hide resolved
.Where(m => m.Name == "op_Explicit" && m.ReturnType == targetType)
.FirstOrDefault();

if (castMethod != null)
{
_value = JsonValue?.GetObjectValue();
_hasValue = true;
var convertExpression = Expression.Convert(Expression.Convert(Expression, typeof(JsonDynamicValue)), targetType, castMethod);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this expression be cached instead since it varies only by type?

If so you can move the cache initialization code in a static constructor or it might involve unreadable code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gvkries are you able to address the last comment so we can merge this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These expressions are wrapping another expression from the instance property Expression. We cannot cache them here.

return new DynamicMetaObject(convertExpression, BindingRestrictions.GetTypeRestriction(Expression, typeof(JsonDynamicValue)));
}

return _value;
// Fallback to default behavior
return base.BindConvert(binder);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class ContentElement : IContent
{
private Dictionary<string, ContentElement> _elements;
private JsonDynamicObject _dynamicObject;
private JsonObject _data;

protected ContentElement() : this([])
{
Expand All @@ -27,7 +28,15 @@ protected ContentElement() : this([])
public dynamic Content => _dynamicObject ??= Data;

[JsonIgnore]
internal JsonObject Data { get; set; }
internal JsonObject Data
{
get => _data;
set
{
_dynamicObject = null;
_data = value;
}
}
gvkries marked this conversation as resolved.
Show resolved Hide resolved

[JsonIgnore]
public ContentItem ContentItem { get; set; }
Expand Down