I am trying to serialize only inherited class properties using json.net. I know about the [JsonIgnore] attribute, but I just want to ignore them for a specific case, so I used a custom JsonConverter instead.
Here is my class:
public class EverythingButBaseJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var classType = value.GetType();
var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
classProps.RemoveAll(t =>
{
var getMethod = t.GetGetMethod(false);
return (getMethod.GetBaseDefinition() != getMethod);
});
var o = (JObject)JToken.FromObject(value);
foreach (var p in o.Properties().Where(p => classProps.Select(t => t.Name).Contains(p.Name)))
p.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
When doing a simple o.WriteTo (writer); it gives the same result as without the use of a converter. When repeating properties and using WriteTo for properties, it works great for the base type (int, string, etc.), but I have a problem with collections.
Expected:
{
"Type": 128,
"Time": [
1,
2,
],
"Pattern": 1,
"Description": ""
}
Got:
"Type": 128,
"Time": [
1,
2,
]"Pattern": 1,
"Description": ""
As you can see, the "," and "endline" snippet is missing from the collection. I also skip global {} for the whole object.
? , ?