RicoSuter / Namotion.Reflection

.NET library with advanced reflection APIs.
MIT License
212 stars 44 forks source link

obj.EnsureValidNullability doesn't seem to work if obj is Dictionary<string, T> #68

Closed orange-puff closed 2 years ago

orange-puff commented 3 years ago

For example

static void Main( string[] args )
        {
            var s = @"
{
    ""a"": {
        ""User"": {
            ""user_name"":""john.mancini"", ""Id"":123
        },
        ""name"":""John Mancini""
    },
    ""b"": {
        ""User"": {
            ""user_name"":""john.mancini"", ""Id"":123
        },
        ""name"":""John Mancini""
    }
}";
            var obj = JsonConvert.DeserializeObject<Dictionary<string, MyClass>>( s );
            obj.EnsureValidNullability();
        }
public class MyClass
    {
        [JsonProperty( "user" )]
        public User User { get; set; } = null!;

        [JsonProperty( "name" )]
        public string Name { get; set; } = null!;
    }

    public class User
    {
        [JsonProperty( "user_name" )]
        public string UserName { get; set; } = null!;

        [JsonProperty( "id" )]
        public int Id { get; set; }
    }

This code throws an error 'Unable to cast object of type 'System.String' to type 'test.MyClass'.' I am not sure if it is known that there are issues related to ensuring the validations of dictionaries. If so, we can delete this issue. A similar error is thrown for Dictionary<int, T>. But T seems to have to be a custom class, or at least not int or string

orange-puff commented 3 years ago

I made a PR with 2 unit tests related to the issue https://github.com/RicoSuter/Namotion.Reflection/pull/69/

jeremyVignelles commented 3 years ago

Dictionary validation is likely indirectly related to #67 (aka Namotion.Reflection is unable to detect nullability in the dictionary).

However, the case you're describing is weird, I don't see where the "cast" occurs. Do you have a stack trace?

Does the deserialization succeed, even when you gave a "User" instead of a "user".

orange-puff commented 3 years ago

Yes, serialization works. But just to be consist I changed "User" to "user" to match the JsonProperty attribute. Here is the stack trace:

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'MyClass'.
   at Namotion.Reflection.ObjectExtensions.ValidateNullability(Object obj, ContextualType type, HashSet`1 checkedObjects, List`1 errors, Boolean stopFirstFail)
   at Namotion.Reflection.ObjectExtensions.ValidateNullability(Object obj, ContextualType type, HashSet`1 checkedObjects, List`1 errors, Boolean stopFirstFail)
   at Namotion.Reflection.ObjectExtensions.EnsureValidNullability(Object obj, Boolean checkChildren)
   at test.Program.Main(String[] args) in C:\Users\john.mancini\Desktop\test\test\Program.cs:line 33
RicoSuter commented 2 years ago

Is this now resolved?

orange-puff commented 2 years ago

I am not sure. I can reopen if you'd like