我知道如何使用自定义 Json Contract Resolver 重命名和删除属性, 而且我知道如何使用自定义 Json Converter 添加属性。
如何在一次序列化中同时使用它们?
我试图同时使用它们创建JsonSerializerSettings,但是合同解析器被序列化忽略了:
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = GetCustomContractResolver(),
Converters = new List<JsonConverter> { GetCustomJsonConverter() }
};
var json = JsonConvert.SerializeObject(myObject, Formatting.Indented, jsonSerializerSettings);
当我单独使用它们时,它们将按预期工作。
这是我的自定义转换器:
public class AddPropertiesJsonConverter : JsonConverter
{
private readonly Dictionary<string, string> m_addedPropertiesDictionary;
public AddPropertiesJsonConverter(Dictionary<string, string> addedPropertiesDictionary)
{
m_addedPropertiesDictionary = addedPropertiesDictionary;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var jObject = (JObject)JToken.FromObject(value);
foreach (var keyValuePair in m_addedPropertiesDictionary)
{
jObject.AddFirst(new JProperty(keyValuePair.Key, keyValuePair.Value));
}
jObject.WriteTo(writer);
}
public override bool CanRead => false;
public override bool CanConvert(Type objectType) => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这是我的自定义合同解析器:
// Rename and delete properties
public class CustomContractResolver : DefaultContractResolver
{
private readonly Dictionary<string, string> m_newSchemaDictionary;
public CustomContractResolver(Dictionary<string, string> newSchemaDictionary)
{
m_newSchemaDictionary = newSchemaDictionary;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
// delete properties
properties = properties.Where(p => m_newSchemaDictionary.ContainsKey(p.PropertyName)).ToList();
// rename
foreach (var property in properties)
{
property.PropertyName = m_newSchemaDictionary[property.PropertyName];
}
return properties;
}
}