2017-07-06 54 views
-2

我試圖通過一些鏈接看,但對我沒有工作,但這個是我:如何返回JSON,而不是在網絡API字符串

[HttpGet] 
public string GetTimes() 
{ 
    var varCheck = checkUser(); 

    if (varCheck.Item1) 
    { 
     using (SqlConnection sc = new SqlConnection(connectionTest)) 
     { 
      try 
      { 
       sc.Open(); 

       using (SqlDataAdapter sda = new SqlDataAdapter("GetTheTimes", sc)) 
       { 
        sda.SelectCommand.CommandType = CommandType.StoredProcedure; 
        sda.Fill(ds); 

        foreach (DataTable table in ds.Tables) 
        { 
         foreach (DataRow row in table.Rows) 
         { 
          listItems.Add(new DataCheck 
          { 
           var1 = row["var1"].ToString(), 
           var2 = row["var2"].ToString() 
          }); 
         } 
        } 
       } 
      } 
      catch (SqlException sqe) 
      { 
       return "There was an error with retrieving the data, please try again later"; 
      } 
      finally 
      { 
       sc.Close(); 
      } 
     } 

     var jsonSerialier = new JavaScriptSerializer(); 
     var json = jsonSerialier.Serialize(listItems); 

     return json; 
    } 
    else 
    { 
     return "Failed"; 
    } 
} 

當API調用它返回與逃脫雙引號。我該如何修改,以便它返回一個純Json對象。

回答

3

試試這個:

[HttpGet] 
//to prevent conflict with HttpGet use inline namespacing 
public System.Web.Mvc.JsonResult GetTimes() 
{ 
    return new System.Web.Mvc.JsonResult { Data = result }; 
} 
+0

感謝。我是否仍然需要使用JavaScriptSerializer函數? – Si8

+0

無論您將哪種類型的數據放入JsonResult的Data屬性,它都會自動序列化。 –

+0

謝謝。我不必序列化了。此外,我曾嘗試過,但我不得不在本地使用System.Web.Mvc.JsonResult而不是導入導致一大堆其他問題的命名空間。在發佈問題之前,我應該更加努力一點,所以我沒有得到-2。謝謝您的幫助。 – Si8

相關問題