Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change json object wrapper name returned from wcf service method

I have created a WCF 3.5 application with a method named TestMe as defined below:

 [OperationContract]
        [WebInvoke(UriTemplate = "/Login", Method = "POST",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        MyDictionary<string, string> TestMe(string param1, string param2);

MyDictionary is created using this link: https://stackoverflow.com/a/7590189/546033

Everything here works fine. But the problem is when returning the data from the implemented method below:

MyDictionary<string, string> success = new MyDictionary<string, string>();
success["desc"] = "Test";
return success;

it returns following json:

{"TestMeResult":{"desc":"Test"}}

while what i need is:

{"success":{"desc":"Test"}}

where success is the object name. What can be the workaround for this?

like image 769
RohitWagh Avatar asked Oct 05 '12 11:10

RohitWagh


2 Answers

You can use MessageParameter attribute.

Controls the name of the request and response parameter names.

[OperationContract]
    [WebInvoke(UriTemplate = "/Login", Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)] 
    [return: MessageParameter(Name = "success")]
    MyDictionary<string, string> TestMe(string param1, string param2);
like image 118
Raj Ranjhan Avatar answered Nov 02 '22 04:11

Raj Ranjhan


Just remove BodyStyle = WebMessageBodyStyle.Wrapped, it defaults to WebMessageBodyStyle.Bare, but have to explicitly declare it yourself.

EDIT:

Since you are dealing with JSON is not going to help becuase it works for XML style. So steps are:

  1. declare it bare so you can send json.
  2. write your own wrapper using json deserializer (http://msdn.microsoft.com/en-us/library/bb412179.aspx)

You may also check this link to find out whats going on internally:

http://msdn.microsoft.com/en-us/library/bb412170.aspx

like image 21
Devela Avatar answered Nov 02 '22 05:11

Devela