[英]Serialize only derived type using Newtonsoft Json.NET
Is there any JsonSerializerSettings available for serializing only the derived type. 是否有任何JsonSerializerSettings可用于仅序列化派生类型。
for example consider i have below two class. 例如,考虑我有两个以下的课程。 When I am serializing Employee object the the result json should only contains the properties of employee not the person class.
当我序列化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;}
}
Questions like those usually reflect an issue with model design, however, one way to do what you want to do is to get rid of the inheritance; 像这样的问题通常反映了模型设计的问题,然而,做你想做的事情的一种方法是摆脱继承; you could try something like converting your object to dynamic and then serialize the dynamic object :
您可以尝试将对象转换为动态,然后序列化动态对象:
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);
}
}
call it like 称之为
MyJson.SerializeObject<Employee>(e, true)
This way you can use it for any type and filter the properties to serialize however you wish in the helper class. 这样,您可以将它用于任何类型,并过滤要在helper类中进行序列化的属性。 For example, you can check the property attributes and decided if it should be added to the dynamic object.
例如,您可以检查属性属性并确定是否应将其添加到动态对象中。
You can use a custom JsonConverter
for that purpose. 您可以使用自定义
JsonConverter
来实现此目的。 Please see below for a basic version for your purpose. 请参阅下面的基本版本以达到您的目的。
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);
}
}
}
After creating your JsonConverter
you can use that during deserialization like below, 创建
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
Please see this link for more information on this 有关此内容的更多信息,请参阅此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.