如何在WCF中传递json字符串并反序列化 [英] how to pass json string and deserialize in WCF

查看:293
本文介绍了如何在WCF中传递json字符串并反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json字符串

I am having a json string

json1 = "{\"Shops\":[{\"id\":\"1\",\"title\":\"AAA\"},{\"id\":\"2\",\"title\":\"BBB\"}],\"movies\":[{\"id\":\"1\",\"title\":\"Sherlock\"},{\"id\":\"2\",\"title\":\"The Matrix\"}]}";

想反序列化并获取requestcollection类中两个类商店和电影中的值.

want to deserialize and get values in two classes shops and movies inside requestcollectionclass.

 [WebInvoke(
               Method = "POST",
               UriTemplate = "SubmitRequest",
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json
               )
        ]
  string SubmitRequest(string RequestDetailsjson);

以及在service.cs

and in the service.cs

JavaScriptSerializer serializer = new JavaScriptSerializer();
            RequestDetailsCollection requestdetailscoll = serializer.Deserialize<RequestDetailsCollection>(RequestDetailsjson);

遇到错误

服务器在处理请求时遇到错误.异常消息是在反序列化类型为System.String的对象时发生错误.来自名称空间"的结尾元素"root".找到名称空间."中的元素"request".有关更多详细信息,请参见服务器日志.异常堆栈跟踪为:

The server encountered an error processing the request. The exception message is 'There was an error deserializing the object of type System.String. End element 'root' from namespace '' expected. Found element 'request' from namespace ''.'. See server logs for more details. The exception stack trace is:

我将参数类型更改为流

string SubmitRequest(Stream RequestDetailsjson);

并更改了代码

StreamReader sr = new StreamReader(RequestDetailsjson);
JavaScriptSerializer serializer = new JavaScriptSerializer();
RequestDetailsCollection requestdetailscoll = (RequestDetailsCollection)serializer.DeserializeObject(sr.ReadToEnd());

出现错误

服务器在处理请求时遇到错误.异常消息是操作'SubmitRequest'的传入消息(合同'IService1',名称空间为' http://tempuri.org/')包含无法识别的http正文格式值'Json'.预期的正文格式值为"Raw".这可能是因为尚未在绑定上配置WebContentTypeMapper.有关更多详细信息,请参见WebContentTypeMapper的文档.有关更多详细信息,请参见服务器日志.异常堆栈跟踪为:

The server encountered an error processing the request. The exception message is 'Incoming message for operation 'SubmitRequest' (contract 'IService1' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is:

帮助我解决此问题

推荐答案

我也遇到了此错误,这是我的解决方法:

I was getting this error too, here's how I fixed it:

我也想要一个Stream,并且在发送Content-Type: application/json时它中断了(如果没有指定内容类型,即Raw没关系).如果对方未指定内容类型,我希望它能正常工作.

I wanted a Stream too and when a Content-Type: application/json is sent it was breaking (was ok if no content-type specified i.e. Raw). I wanted it to work if the other party specified the content-type or not.

因此创建此文件RawContentTypeMapper.cs并将以下内容粘贴到

So create this file RawContentTypeMapper.cs and paste the following in

using System.ServiceModel.Channels;

namespace Site.Api
{

    public class RawContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            // this allows us to accept XML (or JSON now) as the contentType but still treat it as Raw
            // Raw means we can accept a Stream and do things with that (rather than build classes to accept instead)
            if (
                contentType.Contains("text/xml") || contentType.Contains("application/xml")
                || contentType.Contains("text/json") || contentType.Contains("application/json")
                )
            {
                return WebContentFormat.Raw;
            }
            return WebContentFormat.Default;
        }
    }
}

在您的web.config中,您需要指定要使用的内容(<system.serviceModel>部分中的所有以下内容):

In your web.config you need to specify it to be used (all the following in the <system.serviceModel> section):

 <bindings>
    <binding name="RawReceiveCapableForHttps">
        <webMessageEncoding webContentTypeMapperType="Site.Api.RawContentTypeMapper, Site, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
        <httpsTransport manualAddressing="true" maxReceivedMessageSize="524288000" transferMode="Streamed"/>
    </binding>
</bindings>

您还需要更新服务才能使用它:

you'll need to update your service to use this too:

<services>
    <service behaviorConfiguration="XxxBehaviour" name="Site.Api.XXXX">
        <endpoint address="" behaviorConfiguration="web" binding="customBinding" bindingConfiguration="RawReceiveCapableForHttps" contract="Site.Api.IXXXX" />
    </service>
</services>

为了完整起见,这也是我的行为部分

here's my behaviours section too for completeness

<behaviors>
  <serviceBehaviors>
    <behavior name="XxxBehaviour">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>

这篇关于如何在WCF中传递json字符串并反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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