WCF and Json.NET

Apr 20, 2010 at 7:55 AM

Hi,

Any ideas on how to integrate Json.NET into WCF? The DataContractSerializer just sucks when it comes to produce portable Json to be consumed by other languages.

Any pointers will be welcome, I'm in dire need of it.

Cheers!

Coordinator
Apr 20, 2010 at 8:16 AM

No idea.

Aug 4, 2010 at 7:10 AM

LOL.

You'll need to write a wrapper class that inherits from the XmlObjectSerializer.  (In case you're wondering why you're still working with xml ... WCF uses Xml Infoset as its internal data model, http://msdn.microsoft.com/en-us/magazine/cc163447.aspx.)

(Inside the ReadObject and WriteObjectContent, you use the JsonSerializer.)

Then, write an custom operation behavior that derived from DataContractSerializerOperationBehavior; Override the CreateSerializer method to return the wrapper class.

Next, write an endpoint behavior (IEndpointBehavior) that replaces the default binding's DataContractSerializerOperationBehavior with the custom operation behavior.

Finally, you can write either (or both) a custom operation behavior (IOperationBehavior) or a custom behavior extension element (BehaviorExtensionElement) so that you can configure the usage of the JsonSerializer, in code or in the configuration, respectively.

Check Marc Gravell's protocol buffers serialization implementation of the XmlObjectSerializer.

http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/ServiceModel/

 

 

Apr 12, 2011 at 8:38 PM
There appears to be an even simpler way, which does not require deriving from XmlObjectSerializer.
Instead you can implement IDispatchMessageFormatter.SerializeReply in your custom message formater:
    public class WebHttpJsonElement : BehaviorExtensionElement
    {
        public class WebHttpJsonBehavior : WebHttpBehavior
        {
            internal class MessageFormatter : IDispatchMessageFormatter
            {
                Newtonsoft.Json.JsonSerializer serializer = null;
                internal MessageFormatter() 
                {
                    serializer = new Newtonsoft.Json.JsonSerializer();
                }

                public void DeserializeRequest(Message message, object[] parameters)
                {
                    throw new NotImplementedException();
                }

                public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
                {
                    var stream = new MemoryStream();
                    var streamWriter = new StreamWriter(stream, Encoding.UTF8);
                    var jtw = new Newtonsoft.Json.JsonTextWriter(streamWriter);
                    serializer.Serialize(jtw, result);
                    jtw.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    return WebOperationContext.Current.CreateStreamResponse(stream, "application/json");
                }
            }

            protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
            {
                return new MessageFormatter();
            }
        }

        public WebHttpJsonElement() { }

        public override Type BehaviorType 
        {
            get
            {
                return typeof(WebHttpJsonBehavior);
            }
        }

        protected override object CreateBehavior()
        {
            var behavior = new WebHttpJsonBehavior();
            behavior.DefaultBodyStyle = WebMessageBodyStyle.WrappedRequest;
            behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
            behavior.AutomaticFormatSelectionEnabled = false;
            return behavior;
        }
    }
    <behaviors>
      <endpointBehaviors>
        <behavior name="WebHttpJsonBehavior">
          <webHttpJson />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="webHttpJson" type="YourNamespace.WebHttpJsonElement, YourAssembly"/>
      </behaviorExtensions>
    </extensions>
Dec 31, 2015 at 8:16 AM
@an_phu:
It's so complicated for lower developer. Can you give out some example?