WebService默認返回格式是XML,當希望返回Json格式數據時,需要從上下文進行數據輸出。
/// <summary>
/// 查詢數據
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[WebMethod(Description = "查詢數據")]
public void GetData(string Id)
{
Context.Response.Charset = "GB2312"; //設置字符集類型
Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Context.Response.ContentType = "application/json";
try
{
string result = MyDataResultMethod(Id);
Context.Response.Write(result);
}
catch (Exception ex)
{
Context.Response.Write($"服務異常:{ex.Message}");
}
Context.Response.End();
}
Json序列化忽略爲空字段序列
Object obj=new Object();
JsonSerializerSettings sett = new JsonSerializerSettings();
sett.NullValueHandling = NullValueHandling.Ignore;//忽略Null值字段
string result=JsonConvert.SerializeObject(obj, Formatting.Indented, sett);
END |