是否有任何JsonSerializerSettings可用于仅序列化派生类型。
例如,考虑我有两个以下的课程。当我序列化Employee对象时,结果json应该只包含employee的属性而不是person类。public class Person
{
public string Name { get; set; }
}
public class Employee : Person
{
public DateTime JoiningDate { get; set; }
public string EmployeeId { get; set;}
}
答案 0 :(得分:2)
那些问题通常反映了模型设计的问题,然而,做你想做的事情的一种方法是摆脱继承,你可以尝试将对象转换为动态然后序列化动态对象:< / p>
class MyJson
{
public static string SerializeObject<T>(T obj, bool ignoreBase)
{
if(!ignoreBase)
{
return JsonConvert.SerializeObject(obj);
}
var myType = typeof(T);
var props = myType.GetProperties().Where(p => p.DeclaringType == myType).ToList();
var x = new ExpandoObject() as IDictionary<string, Object>;
props.ForEach(p => x.Add(p.Name, p.GetValue(obj, null)));
return JsonConvert.SerializeObject(x);
}
}
称之为
MyJson.SerializeObject<Employee>(e, true)
通过这种方式,您可以将它用于任何类型,并过滤要在helper类中进行序列化的属性。例如,您可以检查属性属性并确定是否应将其添加到动态对象中。
答案 1 :(得分:1)
您可以使用自定义JsonConverter
来实现此目的。请参阅下面的相关基本版本。
public class PersonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(Employee))
return true;
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return "";
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
o.Remove("Name"); //currently the property name is hardcoded. You could enhance this to remove any property you like
o.WriteTo(writer);
}
}
}
创建JsonConverter
后,您可以在反序列化期间使用它,如下所示
var des = JsonConvert.SerializeObject(e, new PersonConverter());
//e is the Person instance we want to convert and PersonConverter is the custom converter
//we use of serialization
有关此内容的详情,请参阅此link