2016-12-28 115 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