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

萝らか妹 提交于 2019-12-12 03:21:48

问题


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:


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"));


来源:https://stackoverflow.com/questions/32098418/producing-json-from-c-webmessagebodystyle-wrapped-or-webmessagebodystyle-bare

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!