Change json object wrapper name returned from wcf service method

I created a WCF 3.5 application with a method called 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 from this link: https://stackoverflow.com/a/464677/

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

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

it returns the following json:

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

while i need:

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

where success is the name of the object. What could be a workaround for this?

+4
source share
2 answers

You can use the 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); 
+6
source

Just remove BodyStyle = WebMessageBodyStyle.Wrapped, it is used by default for WebMessageBodyStyle.Bare, but must explicitly declare it yourself.

EDIT:

Since you are dealing with JSON, this will not help, because it works for the XML style. So the steps are:

  • declare it open so you can send json.
  • create your own shell using json deserializer (http://msdn.microsoft.com/en-us/library/bb412179.aspx)

You can also check this link to find out what is going on inside:

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

+2
source

Source: https://habr.com/ru/post/1437983/


All Articles