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 |