Home >Backend Development >C++ >How Can I Output JSON Instead of XML from an ASMX WebMethod?

How Can I Output JSON Instead of XML from an ASMX WebMethod?

DDD
DDDOriginal
2025-01-15 10:52:43466browse

How Can I Output JSON Instead of XML from an ASMX WebMethod?

Generating JSON Responses from ASMX Web Services

You're working with an ASMX web service and need it to return JSON data instead of the default XML. Even after setting the ResponseFormat property, you're still getting XML.

The solution is to bypass the standard ASMX serialization process and write the JSON directly to the HTTP response. This requires changing the WebMethod's return type to void.

Here's how you can modify your code:

<code class="language-csharp">    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService
    {
        [WebMethod]
        public void WebMethodName()
        {
            string jsonString = "{property: value}"; // Your JSON string here
            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.Write(jsonString);
        }
    }</code>

This revised code directly outputs the JSON string, avoiding the XML wrapper generated by the default ASMX serialization. Remember to replace "{property: value}" with your actual JSON data. Setting the ContentType header ensures the client correctly interprets the response as JSON.

The above is the detailed content of How Can I Output JSON Instead of XML from an ASMX WebMethod?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn