Chris Richardson
Chris Richardson

Reputation: 91

Convert string property value to base64 on serialization

Does anyone know if its possible to convert some of the values in a class to Base64 when you serialize the object? I need a way to mark a property to indicate that it needs to be exported as Base64. For example:

using Newtonsoft.Json;

public class MyFoo {
    public string Value1 { get; set; }

    [ExportThisValueAsBase64]
    public string Value2 { get; set; }
}

public void WriteJSON(MyFoo myFoo) {
    var contentsToWriteToFile = SerializeObject(myFoo, Formatting.Indented);
}

The expected output would then be:

{ "Value1": "A String", "Value2": base64encodedvalue }

I would also need a way to read the values back in from base64 to the string property in the class.

Upvotes: 2

Views: 6411

Answers (1)

Chris Richardson
Chris Richardson

Reputation: 91

What I did in the end was, as advised in the comments, to create a JsonConverter

internal class CustomBase64Converter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {                
        return System.Text.Encoding.UTF8.GetString((Convert.FromBase64String((string)reader.Value)));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {                
        writer.WriteValue(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes((string)value)));
    }           
}

Now on any of my properties I can just add the heading

[JsonConverter(typeof(CustomBase64Converter))]

Upvotes: 7

Related Questions