WebInvoke返回带有额外引号的Json字符串

时间:2012-08-28 08:16:00

标签: c# json wcf post

我正在开发WCF网络服务。 我需要创建一个返回Json string的Post服务,服务声明如下:

[WebInvoke(UriTemplate = "GetMatAnalysis",  ResponseFormat = WebMessageFormat.Json, 
                                                RequestFormat = WebMessageFormat.Json, 
                                                BodyStyle = WebMessageBodyStyle.WrappedRequest, 
                                                Method = "POST")]
string GetMatAnalysis(Stream image);

在此消息中我使用JavaScriptSerializer().Serialize()序列化对象 然后归还。

然而,当我得到答案时,在字符串的开头和结尾都有一个额外的双引号。例如,我得到的是"{"results" : 10 }",而不是{"results" : 10 }

我尝试将返回类型更改为System.ServiceModel.Channels.Message我收到此错误:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: http://tempuri.org/:IMyWebServices ----> System.InvalidOperationException: The operation 'GetMatAnalysis' could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message or a type that has MessageContractAttribute and other parameters of different types. When using System.ServiceModel.Channels.Message or types with MessageContractAttribute, the method must not use any other types of parameters.

如何在没有双引号的情况下返回json字符串?

其他信息:

当我像这样使用GET请求时:

[OperationContract(Name = "Messages")]
[WebGet(UriTemplate = "Messages/GetMessage", ResponseFormat = WebMessageFormat.Json)]
Message GetAdvertisment();

返回类型是消息,它可以正常工作。收到的Json字符串是正确的。

非常感谢任何帮助。 谢谢

2 个答案:

答案 0 :(得分:1)

ResponseFormat = WebMessageFormat.Json开始,WCF服务将您返回的对象序列化为Json。您还可以使用JavaScriptSerializer().Serialize()并获得双序列化。

答案 1 :(得分:0)

返回Stream而不是字符串,并将传出响应的内容类型设置为“ application / json; chatset = utf-8”。这样可以正确返回所有内容。

接口:

[ServiceContract]
interface ITestService
{        
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetMatAnalysis")]
    Stream GetMatAnalysis(Stream image);
}

服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class TestService : ITestService
{
    public Stream GetMatAnalysis(Stream image)
    {
        MatAnalysisResult matAnalysis = new MatAnalysisResult { results = 10 };

        string result = JsonConvert.SerializeObject(matAnalysis);
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

        return new MemoryStream(Encoding.UTF8.GetBytes(result));
    }
}

结果将是:

{"results":10}