How to remove json xml encapsulation returned by Webservice

Asked

Viewed 529 times

5

I created the following method:

[WebService(Namespace = "http://myDomain.com.br/PublicacaoService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class PublicacaoService : CustomWebService
{
    [WebMethod]
    [SoapHeader("UserAuthentication")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public string ObterDiretorios()
    {
        CheckHeader();
        var serializer = new JavaScriptSerializer();
        return serializer.Serialize(new
        {
            title = "Raíz",
            key = "raiz",
            folder = true
        });
    }
    ...
}

But when I make a test by the browser it returns to me the following:

<string xmlns="http://myDomain.com.br/PublicacaoService">
    {"title":"Raíz","key":"raiz","folder":true}
</string>

Well, this model is for example.
I’m mounting a directory tree with the fancytree and I’m doing it this way:

<script type="text/javascript">
    $(function () {
        $("#directoryTree").fancytree({
            source: {
                url: "/Services/PublicacaoService.asmx/ObterDiretorios"
            }
        });
    });
</script>

But when I test, the tree is not created.
And when I try to catch the result json just and play directly on fancytree, works:

<script type="text/javascript">
    $(function () {
        $("#directoryTree").fancytree({
            source: [
                {"title":"Raíz","key":"raiz","folder":true}
            ]
        });
    });
</script>

Which makes me think the encapsulation of the json done with xml is not being recognized by fancytree.

So how do I remove this encapsulation with xml and leave only the value json in return?

1 answer

4


Write the return in Context.Response, not as direct function return:

[WebMethod]
[SoapHeader("UserAuthentication")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void ObterDiretorios()
{
    CheckHeader();
    var serializer = new JavaScriptSerializer();
    string strJSON = serializer.Serialize(new
    {
        title = "Raíz",
        key = "raiz",
        folder = true
    });

    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Flush();
    Context.Response.Write(strJSON);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.