2016-12-28 114 views
1

我有.NET Web服務應該返回結果作爲JSON,但它將它作爲XML返回?這是我的代碼。.NET WebService返回XML而不是JSON

[WebService(Namespace = "http://tempuri.org/MyService")] 
[ScriptService] 
public class MyService : System.Web.Services.WebService 
{ 
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<MyData> GetMyData(string dataFilter, string param) 
    { 
     if (dataFilter.ToLower() == "filterValue") 
      return getData(param); 
     return null; 
    } 
} 
public class MyData 
{ 
    public string id { get; set; } 
    public string name { get; set; } 
    protected internal MyData() { } 
} 

這裏是web.config中

<system.web> 
<compilation debug="true" targetFramework="4.0"/> 
<httpRuntime/> 
<customErrors mode="Off"/> 
<webServices> 
    <protocols> 
    <add name="HttpGet"/> 
    <add name="HttpPost"/> 
    </protocols> 
</webServices> 
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/> 

編輯 通過數字只有當參數,但路過的時候,它返回內部服務器錯誤Web服務工作正常參數內的字符。我很困惑:O

回答

1

試試這個代碼它可以幫助你。安裝Newtonsoft.Json

代碼

public class HelloWorldData 
    { 
     public String Message; 
    } 

    [WebMethod] 
    public void Select() 
    { 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     Context.Response.Clear(); 
     Context.Response.ContentType = "application/json"; 
     HelloWorldData data = new HelloWorldData(); 
     string sql = "exec YOUR_SP_NAME"; 
     SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.AppSettings["BB_CONSTR"]); 
     DataSet ds = new DataSet(); 
     da.Fill(ds); 
     Context.Response.Write(JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented)); 
    } 
+0

你的代碼返回JSON格式,但它不包含一個對象來解析它。 {[{「Test」:「200」}]}但我希望它返回{「d」:[{「Test」:「200」}]} – user987654

+0

可以分享結果的屏幕截圖。 – Bhavanaditya