【发布时间】:2023-03-29 15:18:01
【问题描述】:
Json.net 有没有办法只指定你想要序列化的属性?或者基于像 Declared Only 这样的绑定标志序列化某些属性?
现在我正在使用JObject.FromObject(MainObj.SubObj); 来获取 SubObj 的所有属性,它是一个遵循 ISubObject 接口的类的实例:
public interface ISubObject
{
}
public class ParentSubObject : ISubObject
{
public string A { get; set; }
}
public class SubObjectWithOnlyDeclared : ParentSubObject
{
[JsonInclude] // This is fake, but what I am wishing existed
public string B { get; set; }
[JsonInclude] // This is fake, but what I am wishing existed
public string C { get; set; }
}
public class NormalSubObject: ParentSubObject
{
public string B { get; set; }
}
如果MainObj.SubObj 是NormalSubObject,它将同时对A 和B 进行序列化,但如果是SubObjectWithOnlyDeclared,它将仅对B 和C 进行序列化并忽略父属性
【问题讨论】:
-
[JsonIgnore]? -
查看这篇关于条件序列化的文章。我发现它很有用。 geekytidbits.com/conditional-serialization-with-json-net
标签: c# serialization attributes json.net