简体   繁体   English

如何在WCF中传递json字符串并反序列化

[英]how to pass json string and deserialize in WCF

I am having a json string 我有一个json字符串

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

want to deserialize and get values in two classes shops and movies inside requestcollectionclass. 想要反序列化并在requestcollectionclass中的两个类商店和电影中获取值。

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

and in the service.cs 并在service.cs中

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

Getting error 遇到错误

The server encountered an error processing the request. 服务器在处理请求时遇到错误。 The exception message is 'There was an error deserializing the object of type System.String. 异常消息是“反序列化类型为System.String的对象时发生错误。 End element 'root' from namespace '' expected. 来自名称空间“”的结尾元素“ root”。 Found element 'request' from namespace ''.'. 从名称空间“。”找到元素“ request”。 See server logs for more details. 有关更多详细信息,请参见服务器日志。 The exception stack trace is: 异常堆栈跟踪为:

I changed the parameter type to stream 我将参数类型更改为流

string SubmitRequest(Stream RequestDetailsjson);

And changed the code 并更改代码

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

And getting error 并得到错误

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'. 异常消息是“操作'SubmitRequest'的传入消息(合同'IService1',名称空间为' http://tempuri.org/ ')包含无法识别的http正文格式值'Json'。 The expected body format value is 'Raw'. 预期的正文格式值为“ Raw”。 This can be because a WebContentTypeMapper has not been configured on the binding. 这可能是因为尚未在绑定上配置WebContentTypeMapper。 See the documentation of WebContentTypeMapper for more details.'. 有关更多详细信息,请参见WebContentTypeMapper的文档。 See server logs for more details. 有关更多详细信息,请参见服务器日志。 The exception stack trace is: 异常堆栈跟踪为:

Help me to resolve this issue 帮我解决这个问题

Long question short, you wanted to know how to deserialise your json message. 长话短说,您想知道如何反序列化您的json消息。 This is how to do it. 这是怎么做的。

 var json1 = "{\"Shops\":[{\"id\":\"1\",\"title\":\"AAA\"},{\"id\":\"2\",\"title\":\"BBB\"}],\"movies\":[{\"id\":\"1\",\"title\":\"Sherlock\"},{\"id\":\"2\",\"title\":\"The Matrix\"}]}";
 var requestDetailsCollection = JsonConvert.DeserializeObject<RequestDetailsCollection>(json1);

Your entity classes should be like this. 您的实体类应该是这样的。 (Code Generated using Paste Special) (使用选择性粘贴生成的代码)

public class RequestDetailsCollection 
{
    public Shop[] Shops { get; set; }
    public Movie[] movies { get; set; }
}

public class Shop
{
    public string id { get; set; }
    public string title { get; set; }
}

public class Movie
{
    public string id { get; set; }
    public string title { get; set; }
}

Since there is no code for the RequestDetailsCollection I used json2csharp to convert your json to an object: 由于没有针对RequestDetailsCollection代码,因此我使用json2csharp将json转换为对象:

public class Shop
{
    public string id { get; set; }
    public string title { get; set; }
}

public class Movie
{
    public string id { get; set; }
    public string title { get; set; }
}

public class RequestDetailsCollection
{
    public List<Shop> Shops { get; set; }
    public List<Movie> movies { get; set; }
}


Deserializing like this: 像这样反序列化:

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


Returned: 回来:

在此处输入图片说明

Thanks for the reply . 谢谢回复 。 I have two list<> of different classes inside one class i want to pass json string and serialize . 我想在一个类中有两个list <>不同的类,我想传递json字符串并进行序列化。

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

And in service code JavaScriptSerializer serializer = new JavaScriptSerializer(); 在服务代码中,JavaScriptSerializer serializer = new JavaScriptSerializer(); RequestDetailsCollection requestdetailscoll = serializer.Deserialize(RequestDetailsjson); RequestDetailsCollection requestdetailscoll = serializer.Deserialize(RequestDetailsjson);

Getting error in POSTMAN REST Client The server encountered an error processing the request. 在POSTMAN REST Client中获取错误服务器在处理请求时遇到错误。 The exception message is 'There was an error deserializing the object of type System.String. 异常消息是“反序列化类型为System.String的对象时发生错误。 End element 'root' from namespace '' expected. 来自名称空间“”的结尾元素“ root”。 Found element 'request' from namespace ''.'. 从名称空间“。”找到元素“ request”。 See server logs for more details. 有关更多详细信息,请参见服务器日志。 The exception stack trace is: 异常堆栈跟踪为:

Passing stream param like string SubmitRequest(Stream RequestDetailsjson); 传递像字符串SubmitRequest(Stream RequestDetailsjson)这样的流参数; Getting Below error 低于错误

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'. 异常消息是“操作'SubmitRequest'的传入消息(合同'IService1',名称空间为' http://tempuri.org/ ')包含无法识别的http正文格式值'Json'。 The expected body format value is 'Raw'. 预期的正文格式值为“ Raw”。 This can be because a WebContentTypeMapper has not been configured on the binding. 这可能是因为尚未在绑定上配置WebContentTypeMapper。 See the documentation of WebContentTypeMapper for more details.'. 有关更多详细信息,请参见WebContentTypeMapper的文档。 See server logs for more details. 有关更多详细信息,请参见服务器日志。 The exception stack trace is: 异常堆栈跟踪为:

I was getting this error too, here's how I fixed it: 我也收到了此错误,这是我的解决方法:

I wanted a Stream too and when a Content-Type: application/json is sent it was breaking (was ok if no content-type specified ie Raw). 我也想要一个流,并且在发送Content-Type: application/json它中断了(如果没有指定内容类型,那就是Raw)。 I wanted it to work if the other party specified the content-type or not. 如果对方指定了内容类型,我希望它能正常工作。

So create this file RawContentTypeMapper.cs and paste the following in 因此,创建此文件RawContentTypeMapper.cs并将以下内容粘贴到

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;
        }
    }
}

In your web.config you need to specify it to be used (all the following in the <system.serviceModel> section): 在您的web.config中,您需要指定要使用的内容( <system.serviceModel>部分中的所有以下内容):

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM