I want to replace the default WCF JSON (for all data types) serialization with JSON.NET. I\'ve searched all over the net and couldn\'t find a working solution.
This
Anyway, I figured out a way to use a different serializer, manually, seems its more efficient and faster because it doesn't pass through Microsoft's serializer, although code wise it's a bit messier.
Set all return types as "System.ServiceModel.Channels.Message" in your Interfaces and classes implementing them.
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
System.ServiceModel.Channels.Message GetData();
Create an extension method so you could easily build a memory stream out of an object, using the JSON.NET serializer (or whichever you want to use).
public static System.ServiceModel.Channels.Message GetJsonStream(this object obj)
{
//Serialize JSON.NET
string jsonSerialized = JsonConvert.SerializeObject(obj);
//Create memory stream
MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(jsonSerialized));
//Set position to 0
memoryStream.Position = 0;
//return Message
return WebOperationContext.Current.CreateStreamResponse(memoryStream, "application/json");
}
In the method's body, return the object serialized directly to the stream
return yourObject.GetJsonStream();