Avoiding default constructors and public property setters

后端 未结 1 1298
Happy的楠姐
Happy的楠姐 2020-12-04 00:24

I\'m working on a project with SignalR, and I\'ve got some objects that I\'m going to be passing along through it. These objects are only explicitly created in my back-end

相关标签:
1条回答
  • 2020-12-04 01:16

    If your class does not have a public parameterless constructor, but does have a single public constructor with parameters, Json.NET will call that constructor, matching the constructor arguments to the JSON properties by name using reflection and using default values for missing properties. Matching by name is case-insensitive, unless there are multiple matches that differ only in case, in which case the match becomes case sensitive. Thus if you simply do:

    public class Message
    {
        public string Text { get; private set; }
        public int Awesomeness { get; private set; }
        public Message(string text, int awesomeness)
        {
            if (awesomeness < 1 || awesomeness > 5)
            {
                throw new ArgumentOutOfRangeException("awesome");
            }
            this.Text = text;
            this.Awesomeness = awesomeness;
        }
    }
    

    You will be able to serialize and deserialize your class successfully with Json.NET.

    Prototype fiddle.

    If your class has multiple public constructors, all with parameters, you can mark the one to use with [JsonConstructor], e.g.:

    public class Message
    {
        public string Text { get; private set; }
        public int Awesomeness { get; private set; }
    
        public Message(string Text)
            : this(Text, 1)
        {
        }
    
        [JsonConstructor]
        public Message(string text, int awesomeness)
        {
            if (awesomeness < 1 || awesomeness > 5)
            {
                throw new ArgumentOutOfRangeException("awesome");
            }
            this.Text = text;
            this.Awesomeness = awesomeness;
        }
    }
    

    See also JsonSerializerSettings.ConstructorHandling which tells Json.NET whether to prefer a non-public parameterless constructor over a single public constructor with parameters.

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