3

我正在使用以 JSON 格式响应的 WCF RESTfull 服务,但默认情况下,WCF 服务发送格式不正确的 JSON 消息(我的意思是没有制表的 json 对象)。

默认情况下,WCF 会像这样发送 JSON:

{"ResponseBody":{"Code":"0011","InvocationTime":278,"Message":""},"ResponseInformation":{"ServiceCode":0,"ServiceMessage":"Successfull","ServiceInvocationTime":0}}

但我需要这个:

{
"ResponseBody": {
    "Code": "0011",
    "InvocationTime": 278,
    "Message": ""
},
"ResponseInformation": {
    "ServiceCode": 0,
    "ServiceMessage": "Successfull",
    "ServiceInvocationTime": 0
}

有人知道这个简单问题的解决方案吗?谢谢!

4

2 回答 2

2

您可以使用Json.NET。添加对库的引用(也可作为 NuGet 包提供)并添加

using Newtonsoft.Json;

到你的类文件。然后,执行以下操作:

var json = "{\"ResponseBody\":{\"Code\":\"0011\",\"InvocationTime\":278,\"Message\":\"\"},\"ResponseInformation\":{\"ServiceCode\":0,\"ServiceMessage\":\"Successfull\",\"ServiceInvocationTime\":0}}";
var formattedJson = JsonConvert.DeserializeObject(json).ToString();
于 2013-03-07T14:35:25.253 回答
0

通常 wcf 以 xml 格式响应。因此,如果您在 json 中指定该响应,它将以 jason 格式给出结果。以下示例为 xml 格式的请求和 json 格式的响应。

 [OperationContract]
    [WebInvoke(Method = "GET",
        RequestFormat = WebMessageFormat.Xml,
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare,
       UriTemplate = "GetAllcustomer")]
   List< CustomerResponse> GetAllCustomerDetails();
于 2013-03-07T14:21:33.917 回答