I've almost solved my problem but missing the last piece...
I Have a list of object and I want to be able to add value types (that normaly will be serialized to strings) and get them back as the original type. For example: Guids or custom value types.
This is a sample custom value type:
public struct ExtString
{
private String Value
{
get;
set;
}
public static implicit operator ExtString(String str)
{
return !String.IsNullOrWhiteSpace(str) ? new ExtString(str) : null;
}
public static implicit operator String(ExtString exStr)
{
return exStr.ToString();
}
public ExtString(String str)
{
this.Value = str;
}
public override String ToString()
{
return this.Value;
}
}
This is the Custom converter:
public class CustomConverter : JsonConverter
{
public override Boolean CanConvert(Type objectType)
{
return objectType.IsValueType;
}
public override bool CanRead => false;
public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("$type");
writer.WriteValue(value.GetType().AssemblyQualifiedName);
writer.WritePropertyName("$value");
writer.WriteValue(value.ToString());
writer.WriteEndObject();
}
And here is the sample code for serializing / deserilizing:
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
Converters = new JsonConverter[]
{
new CustomConverter()
}
};
var list = new List<Object>();
list.Add(Guid.NewGuid());
list.Add((ExtString)"Hello World");
var ser = JsonConvert.SerializeObject(list, Formatting.Indented, jsonSerializerSettings);
var deser = JsonConvert.DeserializeObject(ser, jsonSerializerSettings);
This works almost all the way... Both the Guid and ExtString is serialized correct and the Guid is even deserialized with correct value (without special handling!), and the ExtString is created correct (on deserialize) but with the value null (constructor is called but str is null).
What am I missing? Why does it work for Guid?
Thanks.