From 741961fbbd6560c653fe4fccb4a80729e23cb919 Mon Sep 17 00:00:00 2001 From: olfek <27283110+olfek@users.noreply.github.com> Date: Mon, 6 Jul 2026 13:55:43 +0100 Subject: [PATCH 1/2] [Read][JsonToken.String] Check conversion operators to determine if `objectType` is assignable from `byte[]` https://learn.microsoft.com/dotnet/csharp/language-reference/operators/user-defined-conversion-operators --- .../Serialization/JsonSerializerInternalReader.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index d8c163d3e..1d3a5266d 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -327,7 +327,15 @@ private JToken CreateJObject(JsonReader reader) string s = (string)reader.Value!; // string that needs to be returned as a byte array should be base 64 decoded - if (objectType == typeof(byte[])) + if ( + objectType == typeof(byte[]) || + contract != null && + contract.NonNullableUnderlyingType + .GetMethods() + .Where(a => a.GetParameters().Length == 1 && (a.Name == "op_Explicit" || a.Name == "op_Implicit")) + .Select(a => a.GetParameters().Single()) + .Any(a => a.ParameterType == typeof(byte[])) + ) { return Convert.FromBase64String(s); } From 6e4c81778c88aa29673c4a79c8d4fc3de62623a3 Mon Sep 17 00:00:00 2001 From: Rizwaan Bhikha Date: Mon, 6 Jul 2026 15:47:32 +0100 Subject: [PATCH 2/2] Fix `System.InvalidCastException` ``` Unable to cast object of type 'System.Byte[]' to type 'System.Nullable`1[System.Memory`1[System.Byte]]'. at SetData(Object, Object) at Newtonsoft.Json.Serialization.DynamicValueProvider.SetValue(Object target, Object value) ``` --- .../Serialization/JsonSerializerInternalReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 1d3a5266d..5e131e65e 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -337,7 +337,7 @@ private JToken CreateJObject(JsonReader reader) .Any(a => a.ParameterType == typeof(byte[])) ) { - return Convert.FromBase64String(s); + return EnsureType(reader, Convert.FromBase64String(s), CultureInfo.InvariantCulture, contract, objectType); } // convert empty string to null automatically for nullable types