using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Reflection;
public interface IParent
{
[JsonProperty]
int Id {get;set;}
}
[JsonObject(MemberSerialization.OptIn)]
public class Parent : IParent
{
public int Id { get;set; }
public string Name {get;set;}
}
public class Serializer
{
public static void Main()
{
var parent = new Parent() { Id = 1, Name ="Parent"};
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
};
var output = JsonConvert.SerializeObject(parent, Formatting.None, settings);
Console.WriteLine(output);
Console.ReadKey();
}
}
In the above code, the output is {}. Is it possible to serialize and get the output as {“Id”:1}?
This is a bad idea.
Having said that, Newtonsoft provides a way for you to change what’s serialized: in this case, you’d subclass
DefaultContractResolverand overrideCreateProperty.The problem is, it isn’t easy to decide when you should opt-in to serialization based on an interface’s attributes. For one thing, a class could potentially implement multiple interfaces with conflicting serialization instructions. Moreover, deserializing an object into a variable declared as a conflicting interface (for example) won’t work. It’s fragile and it isn’t secure (it allows external code to specify what data an instance reveals).
If you have to do it, the code below works for your case:
Then, when you’re creating your serializer, pass it an instance of your resolver in the settings: