How to deserialize class without calling a constructor?

后端 未结 4 859
长发绾君心
长发绾君心 2021-01-01 16:38

I\'m using Json.NET in my WCF data service.

Here\'s my class (simplified):

[DataContract]
public class Component
{
    public Component()
    {
              


        
4条回答
  •  轮回少年
    2021-01-01 16:46

    Others already mentioned the second constructor, but using 2 attributes: [JsonConstructor] and [Obsolete] you can do much better than leaving it up to humans to remember which one to call.

        public ChatMessage()
        {   
            MessageID = ApplicationState.GetNextChatMessageID(); // An expensive call that uses up an otherwise free ID from a limited set and does disk access in the process.
        }
    
    
        [JsonConstructor] // This forces JsonSerializer to call it instead of the default.
        [Obsolete("Call the default constructor. This is only for JSONserializer", true)] // To make sure that calling this from your code directly will generate a compiler error. JSONserializer can still call it because it does it via reflection.
        public ChatMessage(bool DO_NOT_CALL_THIS)
        {
        }
    

    [JsonConstructor] forces JsonSerializer to call it instead of the default.
    [Obsolete("...", true)] Makes sure that calling this from your code directly will generate a compiler error. JSONserializer can still call it because it does it via reflection.

提交回复
热议问题