I need to serialize many different objects with Json.NET. I really have no control over the objects being provided, so I'm generically serializing and de-serializing with TypeNameHandling.All.
However, some of these objects cannot be de-serialized. Specifically, I am getting some System.Reflection.RuntimePropertyInfo types. I'd like to handle these in a standardized fashion, as I am unaware of the target type at the time of de-serialization. Nor do I care, as long as the output object type is correct.
I've attempted a CustomCreationConverter typed to PropertyInfo that is defined in JsonSerializerSettings. However, even though CanConvert() is returning true, the CustomCreationConverter's ReadJson() is never utilized.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Json
{
class Program
{
static void Main(string[] args)
{
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
Converters = new JsonConverter[] { new PropertyInfoConverter(), },
};
var propertyInfo = typeof(Test).GetProperty("Name");
var serialized = JsonConvert.SerializeObject(propertyInfo, jsonSerializerSettings);
var deserialized = JsonConvert.DeserializeObject(serialized, jsonSerializerSettings);
}
}
public class Test
{
public string Name { get; set; }
}
public class PropertyInfoConverter : CustomCreationConverter<PropertyInfo>
{
public override bool CanConvert(Type objectType)
{
return typeof(PropertyInfo).IsAssignableFrom(objectType);
}
public override PropertyInfo Create(Type objectType)
{
return null;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null; // This is never invoked, but is where I would attempt to find the PropertyInfo via Reflection searching.
}
}
}
Aucun commentaire:
Enregistrer un commentaire