WebService實現Json格式數據返回

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章