2015-04-02 113 views
0

我儘量讓在使用asp.net 3.5中的JSON Web服務,結果以XML返回這樣的:JSON結果返回在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的解決方案?

任何人有想法嗎?

回答

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包含字符串類型,因此它會嘗試返回字符串作爲響應。所以,我們需要發送響應作爲對象。

我也有同樣的問題

找到解決辦法從這裏https://stackoverflow.com/a/5392932/2630817

+0

謝謝。 obj [0]從哪裏來或定義? – 2015-04-02 13:42:03

+0

@HaroldWren它只是一個例子,你可以寫你自己的。它只是我正在使用的一個對象 – 2015-04-03 04:44:05