简体   繁体   中英

ASP.NET Webservice - Returning JSON

I have a web-service called SalesService, which returns the info as a "SalesInfo" instance. This web-service will be called from a Windows application.

I want to know whether its possible to send the result from web-service in a JSON format?.

Remember here its being called from a Windows app not from a web app. I want to know how we can send JSON from webservice to a windows app.. so that XML serialization wont happen.

Thanks

It depends on the type of web service you have.

  • If it's WCF, you can use the WebInvoke attribute and WebMessageFormat.Json to set a JSON response. See this post for an example.

  • If you're using an ASP.NET MVC project and want to return JSON, use the Json object :

For example:

public JsonResult Index()
{
    return Json(new { name = "John Doe" });
}
  • If you're using WebAPI, you need to set the Content-Type header on the request, and WebAPI will take care of the rest.

Sending a response in JSON is possible and is relatively straight forward. It is up to the client to decipher it.

The windows app will need to deserialise the JSON result from the webapp. There is a JSON Library in .NET 4 in the System.Runtime.Serialization.Json namespace. If you need it for an earlier verion, you may need to check out JSON.Net - http://james.newtonking.com/pages/json-net.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM