首页 > 解决方案 > 通用类的自定义 JSON.Net 序列化程序

问题描述

考虑以下程序(请忽略加密并没有真正加密任何东西,它与问题无关):

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);
        }
    }
}

这会生成以下 JSON:

{
  "PersonId": 100,
  "pd": "F",
  "NationalID": {
    "EncryptedData": "49804389043-ABCD5678",
    "DecryptedData": "49804389043"
  },
  "Income": {
    "EncryptedData": "50000-ABCD5678",
    "DecryptedData": 50000
  }
}

我想出了如何为“常规”类实现自定义序列化程序(PersonDemographicsSerializer)。但是,我只是不知道如何为泛型类做同样的事情。

所需的 JSON 输出应仅包含NationalIDIncome值的 DecryptedData 属性,并且应如下所示:

{
  "PersonId": 100,
  "pd": "F",
  "NationalID": "49804389043",
  "Income": 50000
  }
}

标签: c#genericsjson.net

解决方案


推荐阅读