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

后端 未结 2 1054
眼角桃花
眼角桃花 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<int, int> CS$<>9__CachedAnonymousMethodDelegate1;
    
        [CompilerGenerated]
        private static int <get_TotalWithLambda>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<int, int>. 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..

    0 讨论(0)
  • 2021-01-14 07:02

    I've changed IgnoreSerializableAttribute to true by default in release 3 which undoes the breaking change introduced in release 2 - http://json.codeplex.com/releases/view/85975

    You can read more about it here - http://json.codeplex.com/discussions/351981

    0 讨论(0)
提交回复
热议问题