Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing JSON string to Match WCF Service Function Parameter

Tags:

json

rest

c#

wcf

I am facing problem serializing an object in JSON to match parameter name of WCF function call. The problem is to map the parameter name, i.e. the incoming JSON string should have the starting value as the same name as the parameter being passed in the function e.g.

"{\"GetComplexDataResult\":{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}}"

This is my WCF Function which I call in my client and as you can see the parameter name is same as the one which is being returned "GetComplexDataResult"

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
String SaveData(CompositeType GetComplexDataResult);

The problem which occurs is when I try to serialize my object using either Microsoft System.Web.Script.Serialization.JavaScriptSerializer or any other library (e.g. Json.NET)

it only returns me {\"BoolValue\":true,\"StringValue\":\"Hello World!\"} even if I pass an object of the same class "CompositeType" (This is the client side code) e.g.

CompositeType GetComplexDataResult= new CompositeType();
GetComplexDataResult.BoolValue = true;
GetComplexDataResult.StringValue = "Hello World";

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(patchVersion);

My question is how can I get this JSON string

"{\"GetComplexDataResult\":{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}}"

Instead of

{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}

with by just passing my object to JSON parser. I can concatenate it manually after I generate my JSON string, but that would be too much time consuming work. Is there any parser which solves this problem.

like image 777
adnangohar Avatar asked Dec 12 '11 14:12

adnangohar


1 Answers

If you serialize an anonymous object using the parameter name as a property name, it will include it in the json string. Try this:

string json = serializer.Serialize(new { GetComplexDataResult = patchVersion});

Also, if you don't care whether the parameter name is included in the JSON at all, you can set the BodyStyle to BodyStyle = WebMessageBodyStyle.Bare.

like image 185
Jeff Ogata Avatar answered Oct 20 '22 06:10

Jeff Ogata