Search code examples
jsonjson.netbase64jsonconverter

Implementation custom Newtonsoft JsonConverter (reader)


I have an object that is written to Json using a custom Newtonsoft Jsonconverter. The object has two variables (array of vec3 points and array of triangleindices). The values need to be stored as base64 strings inside the json.

The writer works as expected, but I can't figure out how to read the data back in and recreate the object.

The object class definition:

public class Outline
{
    [JsonConverter(typeof(ObjectToBase64Converter))]
    public vec3[] Points { get; set; }
    [JsonConverter(typeof(ObjectToBase64Converter))]
    public int[] TriangleIndices { get; set; }
}

The custom Json converter:

internal class ObjectToBase64Converter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // ?? I've got no clue ??

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            new BinaryFormatter().Serialize(memoryStream, value);
            string base64String = Convert.ToBase64String(memoryStream.ToArray());
            writer.WriteValue(base64String);
        }
    }
}

Any help would be greatly appreciated, I've been stuck on this for hours.


Solution

  • You could define it as following

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        // Convert the Base64 Value to Bytes
        var dataBytes = Convert.FromBase64String(token.Value<String>());
        // Deserialize the Binary Formatted Data
        using (MemoryStream ms = new MemoryStream(dataBytes))
        {
            IFormatter br = new BinaryFormatter();
            return Convert.ChangeType(br.Deserialize(ms),objectType);
        }
    }