假设下面的虚拟示例
internal abstract class Individual
{
public string Name { get; set; }
public abstract bool IsMammal { get; }
}
internal class Human : Individual
{
public override bool IsMammal => true;
// other properties...
}
internal class Eagle : Individual
{
public override bool IsMammal => false;
// other properties...
}
并且我们有一个要序列化的栖息地。
internal class Habitat
{
public List<Individual> Inhabitants;
}
现在,对于所有那些包含IsMammal == true
的个体,我想要序列化整个对象。但是对于那些有IsMammal == false
的人,我想简单地写下名字。使得列表Inhabitants
Inhabitants = new List<Individual> { new Human { Name = "Frank" }, new Eagle { Name = "Brucie" } };
将被序列化为JSON,如下所示
{
Inhabitants = [
{
Name = "Frank",
// Other properties
},
"Brucie"
]
}
我们已经在Newtonsoft的文档中查找了很多,并尝试了ContractResolver
和/或CustomConverter
的东西,但我们不能让它工作。文档和在线资源讨论了如何序列化特定的类,但从未有条件地对属性进行序列化。例如,我们已经尝试过
class IndividualJsonConverter: JsonConverter<Individual>
{
public override void WriteJson(JsonWriter writer, Individual value, JsonSerializer serializer)
{
if (!value.IsMammal)
{
// TODO > Write away name only.
}
else
{
base.WriteJson(writer, value, serializer);
}
}
}
但是没有base.WriteJson
这样的东西,因为这是抽象的。
我不喜欢任何花哨的自定义转换器和序列化器。恕我直言,这段代码非常清晰
var jsonObj=new JObject();
var jArray=new JArray();
jsonObj.Add("Inhabitans",jArray);
foreach (var item in inhabitants )
{
if (item.IsMammal) jArray.Add(JObject.FromObject(item));
else jArray.Add(item.Name);
}
var json=jsonObj.ToString();
json
{
"Inhabitans": [
{
"IsMammal": true,
"Name": "Frank"
},
"Brucie"
]
}