By default, Json.NET will try to serialize the properties of the stream, which isn't very useful. You can modify the behavior by creating your own contract resolver. Here's an example that ignores all Stream
s entirely:
public class IgnoreStreamsResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization
)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (typeof(Stream).IsAssignableFrom(property.PropertyType))
{
property.Ignored = true;
}
return property;
}
}
Use it like:
var bytes = new byte[] { 1, 2, 3 };
var eo = new EventObject { OtherValue = 2, MyStream = new MemoryStream(bytes) };
var s = JsonConvert.SerializeObject(eo,
new JsonSerializerSettings { ContractResolver = new IgnoreStreamsResolver() });
// {"OtherValue":2}
By modifying other properties of the JsonProperty
, you can make other changes. The one that looks like it might be most useful to you is Converter
, which would let you specify your own class to define how to serialize the Stream
(e.g. convert it to a byte[]
and serialize that as base64).
All of this is done without any changes to the interface or implementing class.