如果你想这样做是因为你想指定如何将Person
序列化为 JSON,我认为更好的解决方案是使用自定义JsonConverter
. 转换器可能看起来像这样:
class PersonConverter : JsonConverter
{
public override void WriteJson(
JsonWriter writer, object value, JsonSerializer serializer)
{
var person = (Person)value;
serializer.Serialize(
writer,
new
{
Name = person.LastName,
Age = (int)(DateTime.Now - person.BirthDate).TotalDays / 365
});
}
public override object ReadJson(
JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Person);
}
}
然后你可以像这样使用它:
JsonConvert.SerializeObject(yourObject, new PersonConverter())