Inheritance from Jobject Newtonsoft

前端 未结 1 1832
遇见更好的自我
遇见更好的自我 2021-01-19 15:59

Inheritance from Jobject(Newtonsoft) the existents properties from class not serialized.

Why were the Id and Name properties not serialized?

public c         


        
相关标签:
1条回答
  • 2021-01-19 16:21

    Whatever is the reason you want to do that - the reason is simple: JObject implements IDictionary and this case is treated in a special way by Json.NET. If your class implements IDictionary - Json.NET will not look at properties of your class but instead will look for keys and values in the dictionary. So to fix your case you can do this:

    public class Test : JObject
    {
        public int Id
        {
            get { return (int) this["id"]; }
            set { this["id"] = value; }
        }
    
        public string Name
        {
            get { return (string) this["name"]; }
            set { this["name"] = value; }
        }
    }
    

    If you just want to have both dynamic and static properties on your object - there is no need to inherit from JObject. Instead, use JsonExtensionData attribute:

    public class Test {
        public int Id { get; set; }
        public string Name { get; set; }
    
        [JsonExtensionData]
        public Dictionary<string, JToken> AdditionalProperties { get; set; } = new Dictionary<string, JToken>();
    }
    
    var test = new Test();
    test.AdditionalProperties["new_pro"] = 123456;
    test.Id = 1;
    test.Name = "Dog";            
    var r = Newtonsoft.Json.JsonConvert.SerializeObject(test);
    
    0 讨论(0)
提交回复
热议问题