我尝试使用asp.net 3.5创建一个JSON Web服务,结果以xml形式返回:
<string xmlns="http://.../">
[{"HatId":9,"HatAdi":"SARISU - GÜZELOBA","LevhaAciklama":"KL08"}]
</string>
我使用了LINK示例,我意识到该示例也作为xml返回。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HatlarJSON(String HatAdi)
{
Hatlar[] allRecords = null;
string sql = "SELECT * FROM Table";
SqlConnection con = new SqlConnection("Data Source="ip";Initial Catalog="";User Id="";Password="";Integrated Security=False");
con.Open();
using (var command = new SqlCommand(sql, con))
{
using (var reader = command.ExecuteReader())
{
var list = new List<Hatlar>();
while (reader.Read())
list.Add(new Hatlar { HatId = reader.GetInt32(0), HatAdi = reader.GetString(1), LevhaAciklama = reader.GetString(2) });
allRecords = list.ToArray();
}
}
return new JavaScriptSerializer().Serialize(allRecords);
}
如何在没有xml的情况下返回解决方案?
有人有想法吗?
答案 0 :(得分:1)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HatlarJSON(String HatAdi)
{
Hatlar[] allRecords = null;
string sql = "SELECT * FROM Table";
SqlConnection con = new SqlConnection("Data Source="ip";Initial Catalog="";User Id="";Password="";Integrated Security=False");
con.Open();
using (var command = new SqlCommand(sql, con))
{
using (var reader = command.ExecuteReader())
{
var list = new List<Hatlar>();
while (reader.Read())
list.Add(new Hatlar { HatId = reader.GetInt32(0), HatAdi = reader.GetString(1), LevhaAciklama = reader.GetString(2) });
allRecords = list.ToArray();
}
}
Context.Response.Write( Newtonsoft.Json.JsonConvert.SerializeObject(allRecords));
//this is what I'm using
Context.Response.Write( JavaScriptSerializer().Serialize(allRecords)); //your code
}
您的 webmethod 包含字符串类型,因此它会尝试将字符串作为响应返回。所以,我们需要将响应作为对象发送。
我也有同样的问题