I am a noob to ASP.NET/C#. I am trying to use a web service to return a JSON object from the database. I am getting an error in Firebug that I am creating a circular reference. The stack trace is in JSON format. When I view the web service directly in the browser, it is returning valid XML for some strange reason. Here is my web service.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataSet Posts() {
string connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["XXX"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "SELECT * FROM Posts";
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
I’m new to C# so I don’t know if this is written correctly. What I want is a DataSet in JSON format. Am I doing this correctly? Here is the jQuery that is calling the web service.
<script>
$(function () {
$.ajax({
type: "POST",
url: "WebServices/MessageBoard.asmx/Posts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { console.log(data) },
failure: function (msg) {
//alert(msg);
}
});
});
</script>
The reason you’re getting XML is because the the
DataSetserializes to XML. However, you can use JSON.NET to turn the XML into JSON. Here is an example: