Configure Web Service to respond in JSON

0

good day. I recently developed a WS with several methods, which connect to SQL server. I am trying to consume them through Ajax, researching this topic I found that to perform this action, my WS must respond in JSON format, I understand that natively the WS (developed in Visual) responds in XML format. My doubts are: Is it correct that to consume WS by Ajax, it has to respond in JSON? and the second question is how I configure my WS to respond in JSON format. Attached code of a method:

[WebMethod]
    public String[] InsertxWEBUsers(Session _session, xWEBUsers _xWEBUsers)
    {
        SqlConnection con = new SqlConnection();

        try
        {
            con = this.conection(_session);

            this.check(con);

            xWEBUsers ReleasexWEBUsers = this.initxWEBUsers(con, _xWEBUsers);

            con.Open();

            if (this.validateField(ReleasexWEBUsers.cpnyid.Trim(), ReleasexWEBUsers.custId.Trim(), ReleasexWEBUsers.userId.Trim(), con))
            {
                this.throwException("El UserId " + ReleasexWEBUsers.userId.Trim() + " ya existe en la compañia " + ReleasexWEBUsers.cpnyid.Trim() + " y en el cliente " + ReleasexWEBUsers.custId.Trim() +"");
            }

            this.validatexWEBUsers(ReleasexWEBUsers, con);

            SqlCommand cmd = this.commandInsertxWEBUsers(ReleasexWEBUsers, con);
            cmd.ExecuteNonQuery();


        }

        finally
        {
            con.Close();
        }
        return strArray;
    }

As additional information, researching the internet I found JSON.net a kind of complement to get the WS to respond in JSON, but even so it did not work.

I appreciate your attention, and I remain attentive to your comments, thank you.

Greetings !!!

Annex the Ajax call to invoke my Ws:

$.ajax({
    type: "POST",
    url: "http://devsyshyperv6:8080/xWSRMSUser.asmx/StatusxWEBUsers",
    data: "{ session: '" + session + "', xwEBUsers: " + xwEBUsers + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(r) {
        alert(r.d);
    },
    error: function(r) {
        alert(r.responseText);
    },
    failure: function(r) {
        alert(r.responseText);
    }
});
return false;

Is it correct?

    
asked by iRaver 17.05.2017 в 23:48
source

2 answers

1

Add to your WebMethod

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

Adding this line you say that the response format of your function or method is Json.

    
answered by 18.05.2017 в 00:56
0

is correct, originally the web services are made to return the information in XML format, you could use WCF that has multiple benefits before the web services. But do not be scared, if it is possible that a web service can return the information in Json format, here I leave an excellent tutorial. Greetings.

Json Format Web Service Tutorial

    
answered by 18.05.2017 в 00:50