I want to converts Vectors of the OpenTK library to and from JSON. The way I thought it worked is just making a custom JsonConverter, so I did this:
class VectorConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Vector4);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JToken.Load(reader);
if (obj.Type == JTokenType.Array)
{
var arr = (JArray)obj;
if (arr.Count == 4 && arr.All(token => token.Type == JTokenType.Float))
{
return new Vector4(arr[0].Value<float>(), arr[1].Value<float>(), arr[2].Value<float>(), arr[3].Value<float>());
}
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var vector = (Vector4)value;
writer.WriteStartArray();
writer.WriteValue(vector.X);
writer.WriteValue(vector.Y);
writer.WriteValue(vector.Z);
writer.WriteValue(vector.W);
writer.WriteEndArray();
}
}
Now, the Write part is pretty straight forward to me (I think?). When the serializer goes through objects, if it encounters one that the CanConvert method responds to with true, it lets my custom serializer to convert it to JSON. And that works.
What I don't really get is the other way. Since there's no way to know what type something is when it's just written in literals in JSON, I thought I have to analyse the object myself and determine if it's in fact the Vector object. The code I've written works, but I don't know what to do if the check fails. How do I tell the deserializer that this isn't one of the objects that I know how to translate and that it should do it's default thing on it?
Am I missing something in how the whole thing works?