2015-04-02 140 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