I am creating a C# ASP.NET Web Service application. I need to access data from a SQL database and return this data as XML or JSON. When you run the HelloWorld method (see the code below), it returns the data in XML. But I need to make my own XML tags from the SQL data. How is this done?
In an addition, how can I make the web service use JSON, not XML?
As an example, say I'm returning a table set of 2 rows and 2 columns from SQL and I format it in XML:
<returnSet>
<row1>
<FirstName>
David
</FirstName>
<LastName>
Faustino
</LastName>
</row1>
<row2>
<FirstName>
Henry
</FirstName>
<LastName>
Irons
</LastName>
</row2>
</returnSet>
Thank you very much for any assistance.
UPDATE
I modiifed the code below for the inclusion of returning JSON. The problem is when I debug the application and click on the method, it still shows XML:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">"Hello World"</string>
My expectations have been write the code below, then goto Debug => Start Debugging. Click HelloWorld and, voila, it returns data in the form of JSON. I see elsewhere that some are calling it using jQuery or plain JavaScript. Is that the only way to test that it's returning JSON data?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace WebApplication2
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("Hello World");
}
}
}