0

Being new to WCF, I am trying to figure out the proper configuration to return a JSON object from a WCF service.

The result I am getting is (viewed in firebug):

{"TestServiceResult": "{\"AccountID\":999999,\"CardNumber\":555555,\"AccountBalance\":999.99,\"GivenName\":\"Ben\",\"FamilyName\":\"Rosniak\"}"}

The part I am interested in is one long string and not the JSON object I am after.

The only configuration regarding the service is (the project was started by someone else):

<!-- Added for Mobile Pay Service-->
    <behaviors>
      <serviceBehaviors>
        <behavior name="MobilePayServiceBehaviour" >
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!--<serviceCredentials >
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MobilePayService.WtfUserNamePasswordValidator, MobilePayService" />
          </serviceCredentials>
          <serviceAuthorization principalPermissionMode="Custom">
            <authorizationPolicies>
              <add policyType="MobilePayService.WtfAuthorizationPolicy, MobilePayService" />
            </authorizationPolicies>
          </serviceAuthorization>-->
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="WebHttpBehaviour">
          <webHttp automaticFormatSelectionEnabled="false" defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>

And the test method I am using to make sure the response gets formatted:

[WebGet(UriTemplate = "TestService/{id}/{device}/{culture}")]
public string TestService(string id, string device, string culture)
{
    WCFProfileModel profileModel = new WCFProfileModel()
        {
            AccountID = 999999,
            AccountBalance = 999.99F,
            CardNumber = 555555,
            GivenName = "Ben",
            FamilyName = "Rosniak"
        };

    return profileModel;
}

Somehow the reponse is getting wrapped inside a template of some kind, and I would like know where and how this happens, but I'm not sure where to start looking for this. I would like to strip away the "TestServiceResult" portion and only return:

{"AccountID":999999,"CardNumber":555555,"AccountBalance":999.99,"GivenName":"Ben","FamilyName":"Rosniak"}

UPDATE: I have tried following the tutorial here (updated my code to reflect this), but I get an error "saying profileModel can not be implicitly converted to a string".

Mike D
  • 4,938
  • 6
  • 43
  • 99

3 Answers3

3

Thanks for the responses (and this link), while all helpful in their own particular way, I had to add BodyStyle = WebMessageBodyStyle.Bare as a mehod attribute (thanks @Mehmet Aras).

Returning a string was clearly the WRONG way to go about, and had to change the return type to WCFProfileModel.

In WCFProfileModel, I has to look like:

namespace MyNamspace.PhonePayService.DataModels
{
    [DataContract]
    public class WCFProfileModel
    {
        [DataMember]
        public int AccountID { get; set; }

        [DataMember]
        public int CardNumber { get; set; }

        [DataMember]
        public float AccountBalance { get; set; }

        [DataMember]
        public string GivenName { get; set; }

        [DataMember]
        public string FamilyName { get; set; }
    }
}

This final method looks like:

    [WebGet(UriTemplate = "TestService/{id}/{device}/{culture}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
    public WCFProfileModel TestService(string id, string device, string culture)
    {
        WCFProfileModel profileModel = new WCFProfileModel()
            {
                AccountID = 999999,
                AccountBalance = 999.99F,
                CardNumber = 555555,
                GivenName = "Ben",
                FamilyName = "Rosniak"
            };

        return profileModel;
    }

Something I overlooked completely.

Community
  • 1
  • 1
Mike D
  • 4,938
  • 6
  • 43
  • 99
  • M$ supposedly default it to Bare, but it is not so. JSON response would stop to work without it being set. – Devela Oct 12 '12 at 07:13
2

Try changing defaultBodyStyle in the config from Wrapped to Bare.

Mehmet Aras
  • 5,284
  • 1
  • 25
  • 32
  • Thanks, I did that but I guess I left that out of my update, I will fix that. – Mike D Feb 15 '12 at 20:43
  • I just noticed. The method returns a string but you are returning a WCFProfileModel. You can't do that unless you override ToString method. Why do you not just specify WCFProfileModel as the return type? – Mehmet Aras Feb 15 '12 at 20:48
  • You are absolutely right. I was experimenting with few things and did not copy properly. There other issues also (see below). – Mike D Feb 15 '12 at 20:58
1

I'm not sure I fully understand your question Mike but the best advice I can give you for working with JSON is to grab James Newton King's JSON.NET package. For me it has proven infinitely superior to the base .NET libraries for JSON support and performance. It gives you a ton of control over how you choose to serialize and deserialize your JSON, full LINQ support all kinds of goodies. Give it a look if you haven't checked it out already: http://james.newtonking.com/pages/json-net.aspx

snappymcsnap
  • 2,050
  • 2
  • 29
  • 53