Producing JSON from C#: WebMessageBodyStyle.Wrapped or WebMessageBodyStyle.Bare?

1.1k views Asked by At

I am trying to write a C++ application, using C++ REST SDK lib, that will process JSON data produced by a C# application. A C# program can produce JSON in a "wrapped" or "bare" style.

Using BodyStyle = WebMessageBodyStyle.Wrapped, C# produces JSON like the following:

{"Echo":"{\"firstname\":\"an'",\"number\":21,\"secondname\":\"pn\"}"}

Using BodyStyle = WebMessageBodyStyle.Bare, C# produces JSON like this:

"{\"firstname\":\"an'",\"number\":21,\"secondname\":\"pn\"}"

How can my program recognize which type was produced: Wrapped or Bare?

1

There are 1 answers

0
dsh On

JSON is a standard format for representing, and exchanging, data. It does not define the terms Wrapped or Bare. I am not familiar with C# and its libraries for encoding data as JSON, however I can make a guess based on the samples you provided.

If you have control over the C# application, code it to use Bare only. I see no advantage, in general, to the Wrapped style. Perhaps it is designed specifically for some other C# client libraries.

The only difference I see in the produced output is the structure of the data. There is no way to be absolutely certain, but from those two samples you can simply look at the deserialized object and check if it has an attribute Echo. If it does, use the value of that attribute and if it doesn't then use the object as-is.

Since I haven't worked in C++ in over a decade and I do not know the JSON library you are using, I will give an example in JavaScript (though using a style that may be somewhat closer to C++). Here is how those two objects could be handled:

var data = JSON.parse(...); // the '...' represents where ever you get the text
if (data["Echo"] !== undefined)
    { data = data["Echo"]; }
console.log("The first name is:", data["firstname"]);

Here is a psuedo-code example that is almost valid Java which may be more easily recognized and translated to C++:

Map<String, Object> data = JSON.parse(...); // the '...' represents where ever you get the text
if (data.containsKey("Echo"))
    { data = (Map)data.get("Echo"); }
System.out.println("The first name is: " + data.get("firstname"));