Reputation: 62001
I have some simple .NET objects I'd like to serialize to JSON and back again. The set of objects to be serialized is quite small and I control the implementation, so I don't need a generic solution that will work for everything. Since my assembly will be distributed as a library I'd really like to avoid a dependency on some third-party DLL: I just want to give users one assembly that they can reference.
I've read the other questions I could find on converting to and from JSON in .NET. The recommended solution of JSON.NET does work, of course, but it requires distributing an extra DLL.
I don't need any of the fancy features of JSON.NET. I just need to handle a simple object (or even dictionary) that contains strings, integers, DateTimes and arrays of strings and bytes. On deserializing I'm happy to get back a dictionary - it doesn't need to create the object again.
Is there some really simple code out there that I could compile into my assembly to do this simple job?
I've also tried System.Web.Script.Serialization.JavaScriptSerializer
, but where it falls down is the byte array: I want to base64-encode it and even registering a converter doesn't let me easily accomplish that due to the way that API works (it doesn't pass in the name of the field).
Upvotes: 9
Views: 3144
Reputation: 62001
A possible workaround that allows using the .NET framework JavaScriptSerializer
is to register a converter that base-64 encodes byte arrays into a sub-field, like this:
class ByteArrayBase64Converter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
return Convert.FromBase64String((string)dictionary["b64"]);
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
return new Dictionary<string, object> { { "b64", Convert.ToBase64String((byte[])obj) } };
}
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(byte[])}; }
}
}
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new ByteArrayBase64Converter() });
Upvotes: 4
Reputation: 72658
Json.NET is MIT-licensed, you can you just download the source and include only those files that you need for your application.
Upvotes: 4