Replace default JSON serializer in WCF 4 to JSON.NET

前端 未结 1 1671
忘掉有多难
忘掉有多难 2020-12-09 11:21

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

相关标签:
1条回答
  • 2020-12-09 11:50

    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. 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(); 
      
    2. 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");
      }
      
    3. In the method's body, return the object serialized directly to the stream

      return yourObject.GetJsonStream();
      
    0 讨论(0)
提交回复
热议问题