c# - 将 WCF 4 中的默认 JSON 序列化程序替换为 JSON.NET

标签 c# json wcf c#-4.0 json.net

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

这是我的对象:

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

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

这是我的 WCF 函数:

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

这是 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:

 <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 时得到的:

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

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

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

最佳答案

无论如何,我想出了一种手动使用不同序列化程序的方法,它似乎更高效、更快速,因为它不通过 Microsoft 的序列化程序,尽管在代码方面它有点困惑。

  1. 在您的接口(interface)和实现它们的类中将所有返回类型设置为“System.ServiceModel.Channels.Message”。

    [OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    System.ServiceModel.Channels.Message GetData(); 
    
  2. 创建一个扩展方法,以便您可以使用 JSON.NET 序列化程序(或您想要使用的任何一种)轻松地从对象构建内存流。

    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. 在方法体中,将序列化后的对象直接返回给流

    return yourObject.GetJsonStream();
    

关于c# - 将 WCF 4 中的默认 JSON 序列化程序替换为 JSON.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13659451/

相关文章:

C#如何初始化WebService

c# - 通过 msi 文件在 Windows Mobile 中部署 .Net Compact Framework 应用程序

c# - 找不到与命令 "dotnet-/app/Build\ClearPluginAssemblies.dll"Docker 匹配的可执行文件

php - 如何将Android与PHP和MySQL连接?

ASP.NET -> WCF 服务需要 Windows 身份验证

c# - 从代码隐藏添加的 JS 代码无法运行

ios - 如何快速将json传递给服务器

json - Spark对json的异常处理

c# - 如何配置 WCF 以将 HTTP 与客户端证书一起使用?

wcf - IFrame 回调,服务器响应未出现在客户端上