从Jobject Newtonsoft继承 [英] Inheritance from Jobject Newtonsoft
问题描述
从Jobject(Newtonsoft)继承而来的未序列化类的existents属性.
Inheritance from Jobject(Newtonsoft) the existents properties from class not serialized.
为什么没有对ID和Name属性进行序列化?
Why were the Id and Name properties not serialized?
public class Test : JObject
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var test = new Test();
test["new_pro"] = 123456;
test.Id = 1;
test.Name = "Dog";
var r = Newtonsoft.Json.JsonConvert.SerializeObject(test);
// Result = { "new_pro":123456}
}
}
有什么主意吗?
推荐答案
无论您要这样做的原因是什么-原因很简单:JObject
实现IDictionary
,Json以特殊方式处理这种情况.网.如果您的类实现IDictionary
-Json.NET将不会查看您类的属性,而是会在字典中查找键和值.因此,要解决您的问题,您可以执行以下操作:
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; }
}
}
如果只想在对象上同时具有动态和静态属性,则无需从JObject继承.而是使用JsonExtensionData
属性:
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);
这篇关于从Jobject Newtonsoft继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!