Zote
Zote

Reputation: 5379

WCF + Json = wrong serialization

Why this WCF 3.5 method

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Json
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public string Upper(string text)
    {
        return text.ToUpper();
    }
}

returns {"d":"TEXT"} ?

It should returns {"TEXT"}

I'm calling using jQuery.

    $("#upper").click(function() {
        $.ajax({
            type: "GET",
            url: "/Json.svc/Upper?text="+$("#input1").val(),
            success: function(data) {
                $("#input1").val(data.d);
            }
        });
    });

Upvotes: 3

Views: 6512

Answers (3)

JeremyWeir
JeremyWeir

Reputation: 24388

I'm assuming you are using <enableWebScript/> in your behavior config, replace that with <webHttp defaultOutgoingResponseFormat="Json"/> and you will get json without the root "d" and without the "__type" props.

However, I've only tested this in 4.0

I also don't use any attributes in code.

Upvotes: 1

Brandon Montgomery
Brandon Montgomery

Reputation: 6986

This is a security feature that has been added to the JSON serialization in .NET 3.5. It's a container object, so instead of, say, results[0], you would just say results.d[0]. Read this article for more information.

Upvotes: 8

tomasr
tomasr

Reputation: 13869

Have you tried changing the BodyStyle property of your [WebGet] Attribute so that responses aren't wrapped?

Upvotes: 0

Related Questions