Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft JSON.NET compatibility with Json web services

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

like image 973
Mikey S. Avatar asked Jul 10 '11 13:07

Mikey S.


People also ask

Is Newtonsoft JSON compatible with .NET core?

Text. Json library is included in the runtime for . NET Core 3.1 and later versions. For other target frameworks, install the System.

Is JSON net and Newtonsoft the same?

Text. Json is a new JSON library for . NET with different design goals from its predecessor, Newtonsoft.

Is Newtonsoft JSON still supported?

Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System.

What is Newtonsoft JSON net?

The Newtonsoft. JSON namespace provides classes that are used to implement the core services of the framework. It provides methods for converting between . NET types and JSON types.


2 Answers

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.

like image 54
Darin Dimitrov Avatar answered Sep 19 '22 08:09

Darin Dimitrov


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>
like image 34
DmitryK Avatar answered Sep 19 '22 08:09

DmitryK