i具有.NET Web服务,该网络应该将结果返回为JSON,但它将其返回为XML?这是我的代码。
[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
尝试此代码可能会为您提供帮助。安装 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));
}