将 WCF 4 中的默认 JSON 序列化程序替换为 JSON.NET [英] Replace default JSON serializer in WCF 4 to JSON.NET

查看:21
本文介绍了将 WCF 4 中的默认 JSON 序列化程序替换为 JSON.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 JSON.NET 替换默认的 WCF JSON(适用于所有数据类型)序列化.我搜索了整个网络,但找不到可行的解决方案.

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.

这是我的对象:

    [JsonObject]
public class TestObject
{
    [JsonProperty("JsonNetName")]
    public string Name = "John";

    [JsonProperty]
    public DateTime Date = DateTime.Now;
}

这是我的 WCF 函数:

This is my WCF function:

    [OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    List<TestObject> Get();

这是 Global.asax 中的代码:

This is the code in Global.asax:

        protected void Application_Start(object sender, EventArgs e)
    {
        // Create Json.Net formatter serializing DateTime using the ISO 8601 format
        var serializerSettings = new JsonSerializerSettings();

        serializerSettings.Converters.Add(new IsoDateTimeConverter());
        serializerSettings.Converters.Add(new BinaryConverter());
        serializerSettings.Converters.Add(new JavaScriptDateTimeConverter());
        serializerSettings.Converters.Add(new BinaryConverter());
        serializerSettings.Converters.Add(new StringEnumConverter());

        var config = HttpHostConfiguration.Create().Configuration;

        Microsoft.ApplicationServer.Http.JsonMediaTypeFormatter jsonFormatter = config.OperationHandlerFactory.Formatters.JsonFormatter;

        config.OperationHandlerFactory.Formatters.Remove(jsonFormatter);

        config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));

        var httpServiceFactory = new HttpServiceHostFactory
        {
            OperationHandlerFactory = config.OperationHandlerFactory,
            MessageHandlerFactory = config.MessageHandlerFactory
        };

        //Routing
        RouteTable.Routes.Add(
           new ServiceRoute(
               "Brands", httpServiceFactory,
               typeof(Brands)));

      }

这是 Web.Config:

This is Web.Config:

 <endpointBehaviors>
    <behavior name="Behavior_Brands">
      <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Bare" />
    </behavior>
  </endpointBehaviors>

和服务部分:

<service name="TestApp.CoreWCF.Brands">
    <endpoint address="" behaviorConfiguration="Behavior_Brands" binding="webHttpBinding" contract="TestApp.CoreWCF.IBrands">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
  </service>

最后,这是我在启动 URL 时得到的:

And finally, this is what I'm getting when launching the URL:

"http://localhost:30000/Brands/Get"

[{"Date":"/Date(1354364412708+0200)/","Name":"John"}, {"Date":"/Date(1354364412708+0200)/","Name":"John"}]

JSON 答案显然忽略了 JSON.NET 属性.

The JSON answer obviously ignores the JSON.NET attributes.

推荐答案

总之,我想出了一个方法来使用不同的序列化器,手动的,似乎它更有效更快,因为它不通过微软的序列化器,虽然代码明智的做法是有点乱.

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.

  1. 在您的接口和实现它们的类中将所有返回类型设置为System.ServiceModel.Channels.Message".

  1. 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(); 

  • 创建一个扩展方法,以便您可以使用 JSON.NET 序列化程序(或您想使用的任何一个)轻松地从对象构建内存流.

  • 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();
    

  • 这篇关于将 WCF 4 中的默认 JSON 序列化程序替换为 JSON.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆