How to remove xml encapsulation in json returned by WebService

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 test the browser it returns the following:

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

Well, this template is for example.
I'm setting up a directory tree with fancytree and I'm doing it in the following 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 get the json result only and play directly on fancytree

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

What makes me think that the json encapsulation made with xml is not being recognized by < fancytree .

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

asked by anonymous 12.08.2014 / 18:49

1 answer

4

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

[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);
}
    
12.08.2014 / 19:01