Consider the following program (please ignore that encryption doesn't really encrypt anything, it is not relevant for the question):
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InterfaceSerialize
{
public class PersonDemographicsSerializer: JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var pd = value as PersonDemographics;
serializer.Serialize(writer, pd.Age.ToString("X")); // Convert int age to hex string
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return typeof(PersonDemographics).IsAssignableFrom(objectType);
}
}
[JsonConverter(typeof(PersonDemographicsSerializer))]
public class PersonDemographics
{
public int Age { get; set; }
public string FirstName { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public PersonDemographics pd { get; set; }
public IEncrypted<string> NationalID { get; set; }
public IEncrypted<int> Income { get; set; }
}
public interface IEncrypted<T>
{
T DecryptedData { get; }
string EncryptedData { get; }
}
//[DataContract]
//[JsonConverter(typeof(EncryptedSerializer))]
public class Encrypted<T> : IEncrypted<T>
{
public string EncryptedData { get; set; }
public T DecryptedData { get; set; }
public Encrypted(T input, string password)
{
DecryptedData = input;
EncryptedData = input.ToString() + password;
}
}
class Program
{
static void Main(string[] args)
{
string password = "-ABCD5678";
Person p = new Person { PersonId = 100,
pd = new PersonDemographics { Age = 15, FirstName = "Joe" },
NationalID = new Encrypted<string>("49804389043", password),
Income = new Encrypted<int>(50000, password)
};
string json = JsonConvert.SerializeObject(p);
}
}
}
This generates following JSON:
{
"PersonId": 100,
"pd": "F",
"NationalID": {
"EncryptedData": "49804389043-ABCD5678",
"DecryptedData": "49804389043"
},
"Income": {
"EncryptedData": "50000-ABCD5678",
"DecryptedData": 50000
}
}
I figured out how to implement custom serializer (PersonDemographicsSerializer) for the "regular" class. However, I just can't figure out how to do the same for the generic class.
Desired JSON output should only include DecryptedData property for the values of NationalID and Income and should look like this:
{
"PersonId": 100,
"pd": "F",
"NationalID": "49804389043",
"Income": 50000
}
}