5

I was wondering since I didn't find it anywhere -

Can a Json based web service be used in conjunction with the Json.NET library?

In other words, is there a way to make JSON.NET deserialize the webservice's request's JSON object instead of .NET default Serializer?

One way to do it is probably declare the WebMethod to accept a plain string, and then use JSON.NET's JsonConvert, to deserialize that raw string into the correct object, but that means that the request's syntax (from the client side) will be kind of awkward.

Is there any other ways or suggestions of doing this?

Thanks,

Mikey

Mikey S.
  • 3,301
  • 6
  • 36
  • 55

3 Answers3

3

AFAIK, you have to do this manually, by having your web service take a string as argument and return a string as response. If you use WCF things are much different as the architecture is much more extensible in comparison to classic ASMX web services which by the way are considered a deprecated technology now.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Lets assume i'll be using WCF instead of classic web services, will it be possible to configure a custom serializer and using json.net instead of .net's default serializer? – Mikey S. Jul 10 '11 at 13:20
  • @Mikey S., of course, and by the way WCF doesn't use [`JavaScriptSerializer`](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx) by default but [`DataContractJsonSerializer`](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx). All you need is to write a [custom message formatter](http://stackoverflow.com/questions/3118504/how-to-set-json-net-as-the-default-serializer-for-wcf-rest-service/3131413#3131413). – Darin Dimitrov Jul 10 '11 at 13:23
  • Thanks a lot, any good tutorials/books on WCF in general and on this subject specifically? – Mikey S. Jul 10 '11 at 14:17
3

I've been searching for ways to use JSON.NET to handle JSON serialization. The best approach that I've found is to create a WCF behavior extension by deriving from BehaviorExtensionElement class. It is described here:

http://json.codeplex.com/discussions/209865

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.ServiceModel.Configuration;
using System.ServiceModel.Dispatcher;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class JsonNetBehaviorExtension : BehaviorExtensionElement
{
    public class JsonNetBehavior : WebHttpBehavior
    {
        internal class MessageFormatter : IDispatchMessageFormatter
        {
            JsonSerializer serializer = null;
            internal MessageFormatter()
            {
                serializer = new 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 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 JsonNetBehaviorExtension() { }

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

    protected override object CreateBehavior()
    {
        var behavior = new JsonNetBehavior();
        behavior.DefaultBodyStyle = WebMessageBodyStyle.WrappedRequest;
        behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
        behavior.AutomaticFormatSelectionEnabled = false;
        return behavior;
    }
}

Then in your web.config

<system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="webHttpJson" type="YourNamespace.JsonNetBehaviorExtension, YourAssembly"/>
      </behaviorExtensions>
    </extensions>
    <behaviors>
      <endpointBehaviors>
        <behavior name="NewtonsoftJsonBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
          <webHttpJson/>
        </behavior>
      </endpointBehaviors>
     <behaviors>
DmitryK
  • 31
  • 1
2

The new WCF Web API for REST web services provides a way to use Json.NET as the serializer.

http://blogs.clariusconsulting.net/kzu/using-json-net-for-text-and-binary-json-payloads-with-wcf-webapi/

James Newton-King
  • 48,174
  • 24
  • 109
  • 130