我在网上找到了几种针对WCF Web服务而非ASP Web服务的解决方案。
目前,我正在收到一封JSON响应,上面写着:
{"d":[{"__type":"NetworkFuzzWebSvc.Sessions","BaseUri":"http://localbox","SessionId":"43b8716f-40ab-43bf-8311-575c2ecd2730}]}
我需要它返回:
{"Sessions":["BaseUri":"http://localbox","SessionId":"43b8716f-40ab-43bf-8311-575c2ecd2730}]}
以下是我正在使用的网络服务代码的副本(NetFuzzWebSvc.asmx):
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
namespace NetworkFuzzWebSvc
{
public class Sessions
{
public string BaseUri;
public string SessionId;
}
/// <summary>
/// Summary description for NetFuzzJson
/// </summary>
[WebService(Namespace = "http://localbox")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class NetFuzzJson : WebService
{
List<Sessions> Sessions = new List<Sessions>
{
new Sessions{
BaseUri = "http://localbox/",
SessionId="43b8716f-40ab-43bf-8311-575c2ecd2730"
}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Sessions> GetAllSessions()
{
return Sessions;
}
}
任何人都有解决方案吗? 谢谢!
答案 0 :(得分:2)
删除“d”和“__type”:
.SVC
[ServiceContract]
public interface ITestService
{
[OperationContract]
[WebInvoke(Method = "POST",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
List<TestDTO> GetAll();
}
的.config
<behaviors>
<endpointBehaviors>
<behavior name="DebugJSonBehavior" >
<enableWebScript />
<!--need set automaticFormatSelectionEnabled attribute -->
<webHttp automaticFormatSelectionEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DebugJSonBehavior" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
JS:
$.ajax({
type: "POST",
url: _serviceUrl + "/TestService.svc/GetAll",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (dataret) { ... },
error: function (xmlHttpRequest, textStatus, errorThrown) {... },
complete: function () { ... }
});
答案 1 :(得分:1)
我认为你不能。我认为这是返回的json的格式。
您可以尝试删除ResponseFormat位并返回一个字符串并使用
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(objectClass);
return json;
甚至更好地使用JSON.Net库。
另请参阅How to not serialize the __type property on JSON objects了解如何删除__type位。
答案 2 :(得分:-1)
如果您正在使用ServiceStack.Text JSON Serializer,则只需:
JsConfig.ExcludeTypeInfo = true;
此功能已自动添加回v2.28,但上面的代码将其保留在序列化之外。您还可以通过Type
更改此行为:
JsConfig<Type>.ExcludeTypeInfo = true;