Why does Json.NET serialization fail with [Serializable] and a lambda inside a read-only property?

后端 未结 2 1051
眼角桃花
眼角桃花 2021-01-14 06:06

According to these release notes, Json.NET now supports the SerializableAttribute:

Json.NET now detects types that have the SerializableAttribute and

2条回答
  •  隐瞒了意图╮
    2021-01-14 06:42

    I installed and used JustDecompile and found that the compiler adds a field and a method to the class when the lambda is uncommented:

    public class MyType
    {
        [CompilerGenerated]
        private static Func CS$<>9__CachedAnonymousMethodDelegate1;
    
        [CompilerGenerated]
        private static int b__0(int x) { ... }
    
        // ... plus the other class members ...
    }
    

    When the class has SerializableAttribute on it, Json.NET tries to serialize the private field, but can't since it's of type Func. Removing the SerializableAttribute instructs Json.NET to ignore private fields and so it doesn't cause a problem.

    Update: Json.NET 4.5 release 3 now makes this only a problem if you explicitly set IgnoreSerializableAttribute=false, or it can be resolved by adding the JsonObjectAttribute to the class..

提交回复
热议问题