c# - 通用类的自定义 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 输出应仅包含NationalID和Income值的 DecryptedData 属性,并且应如下所示:
{
"PersonId": 100,
"pd": "F",
"NationalID": "49804389043",
"Income": 50000
}
}
解决方案
推荐阅读
- web-scraping - 如何从 scrapy 项目创建可执行文件?
- sql-server - 将 bcp 与取自另一列的文件名一起使用
- linux - API/CLI 触发 KVM 动作
- javascript - 使用ajax强制注销时数据库表未更新
- spring-boot - Navigator MediaDevices getUserMedia“权限被拒绝”
- macos - Mac OS X,Docker:将容器日志从 Docker for Mac VM 获取到同一 Docker for Mac 中的 ELK 堆栈
- python - 如何将索引应用到另一个数据帧的数据帧
- node.js - Aws lambda 返回承诺
- sql-server - SQL XPath 比较变量与空 XML 节点
- python - 更改列的顺序以创建适合 barplot 的数据框