I m making web service for the first time. and i need to make that using json in c#. I m not getting how to code the methods that fetch data from database Any suggessions.
These days, most public web services provide REST APIs and transfer data in the compact and easy-to-use JSON data-interchange format.
JSON as we know is Javascript Object Notation and is very lightweight and has gained a good momentum to use in such scenarios. Developers now prefer JSON over XML response in a Web Service. Let us create a web Service and see how to return a JSON response from the same. Open Visual Studio.
JSON Web Services let you access portal service methods by exposing them as a JSON HTTP API. Service methods are made easily accessible using HTTP requests, both from JavaScript within the portal and from any JSON-speaking client.
You can use the below code to return the JSON serialized string:
[WebMethod(Description = "Your Description")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string FunctionName()
{
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string retJSON = js.Serialize(Object);
return retJSON;
}
I spent hours Googling around, trying to find a quick, decent, readable way of creating JSON web services.
In the end, when I'd finally worked out how to do it, I went back and documented it, so I never have to face these hurdles again !!
Have a read here
(It's actually for WCF JSON web services, but also shows how to link it to a SQL Server database, and so on.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With