Posting JSON with '\/' gets escaped as '\\/' - c#

I'm currently facing a problem when posting the following JSON Object:
{
"event": "orders.updated",
"address": "http:\/\/82.75.163.12\/BiedMeerIntegration?connectionId=545",
"is_active": true
}
The problem with the above is that .NET escapes all backslash characters and posts it like:
{
"event": "orders.updated",
"address": "http:\\/\\/82.75.163.12\\/BiedMeerIntegration?connectionId=545",
"is_active": true
}
I tried different libraries (like ServiceStack and the Microsoft HttpClient) but they all result in the same error. I don't have control of the REST interface and it specifically accepts the url format stated in the first JSON sample.
I also had a look at the GenericUriParser options in .NET 4 but it seems it doesn't make a difference: http://msdn.microsoft.com/en-us/library/ee656542.aspx
How will I be able to format the request correctly?

The problem is your string:
{
"event": "orders.updated",
"address": "http:\/\/82.75.163.12\/BiedMeerIntegration?connectionId=545",
"is_active": true
}
Is actually already escaped, and in fact is perfectly correct JSON. Note that, both in JavaScript and JSON, escaping the / is optional and only required when such symbol comes after <, in order to prevent unwanted closing of a <script> tag.
The output of your JSON serializer should already look like that (even if those \/ are not really needed, they are correct). So I don't really understand why you are giving a fragment of already-well-formed JSON to a JSON serializer... which then escapes it again. If you already have correct JSON, shouldn't you simply write it to the output stream?
On the contrary, if what you have is the "http:\/\/82.75.163.12\/BiedMeerIntegration?connectionId=545" string coming from somewhere in your application's model or services (and not the already-formed JSON fragment as you show it to us), then the problem is such string is already escaped -in JavaScript or JSON, can be any-, and you should first correctly unescape it in its corresponding language before giving it to the serializer. But don't unescape the JSON fragment above as a whole!... a fragment of JSON without adequate escaping makes no sense, would be simply not JSON.

Related

Corrupted JSON HTTP response

I am getting a HTTP request for a website and the content type is JSON. However, I am getting a nested JSON that is a unicode and is causing consistency problems.
Here is an example:
{"key1":"value",
"key2":"value",
"key3":{
u'key31':u'value',
u'key32':u'value'}}
This reminds me of python 2.7 troubles but I am not sure how to fix this JSON. I am using C# to parse it. Everything works correctly until I try to access key3.
The content should be a JSON object type but it is considered rather a value or a string.
Thanks for ya help. Is there a way to fix it if it is actually corrupted or am I parsing it wrongly?
You're correct that this json object is not complete / does not have the correct syntax. You're missing a closing '}' character.
How are you parsing your data? Try taking a look at this documentation.
your json object is not in valid formatted it should be like as folllows
{
"key1":"value",
"key2":"value",
"key3":{
" u'key31'":"u'value'",
"u'key32'":"u'value'"
}
}
by any chance do you get this json from python dump? coz Python's unicode literals are not valid JSON, and neither are single quotes

CBOR serialization (string escaping)

I was CBOR serializing a JSON object in C++ with nlohmann::json library and my use case involves reading the cbor byte string output in c#. I've noticed that, whereas when dumping a json object to a string in C++ with nlohmann::json library, json string values (i.e., case value_t::string) are escaped (a call to escape_string is made), no such call is made when json values are string values in the CBOR approach.
I was reading the CBOR CRF 7049 and it seems that strings do not need to be escaped when serializing to CBOR.
The behavior in the nlohmann::json library is consistent: strings are not escaped when serializing, nor excepted to be escaped when de-serializing.
But it appears that Newtonsoft.Json (C# library), expects that. Is it a valid expectation? Or am I doing something wrong in the process?
C++ side:
nlohmann::json json_doc;
json_doc["characters"] = nlohmann::json::array();
for (int i = 0; i < characters.size(); i++) {
json_doc["characters"][i]["name"] = (characters[i] != nullptr) ? characters[i]->name() : "";
}
std::vector<uint8_t> cbor = nlohmann::json::to_cbor(json_doc);
output->assign((char*)&cbor[0], cbor.size());
C# side. cbor_bytes is the cbor byte string (c++ output vector)
CBORObject cbor = CBORObject.DecodeFromBytes(cbor_bytes);
output = cbor.ToString();
Such output string by then, is wrongly formed:
{"characters": [{"name": "Clara Oswald"}, {"name": "Kensi Blye"}, {"name": "Temperance "Bones" Brennan"}]}
and cannot, obviously be parsed:
JObject output_obj = JObject.Parse(output);
CBOR (Concise Binary Object Representation) is not JSON (JavaScript Object Notation). Although CBOR may have borrowed some concepts from JSON, it is clearly a different format with different rules and goals. CBOR is a binary format; JSON is text. In CBOR, strings have length prefixes, whereas they do not in JSON. Furthermore, CBOR does not allow arbitrary whitespace between elements (it wouldn't make sense for a binary format), whereas JSON does (for human readability). Ultimately, CBOR does not need a mechanism to escape strings because it does not require delimiters to tell where a string starts and ends. JSON, on the other hand, requires double quotes to mark the beginning and end of each string. As a consequence, quotes and control characters within strings must be escaped with backslashes in JSON, as well as literal backslashes themselves. There is no getting around this rule if you want to ensure the JSON will be parsable.
In your code above you are using the CBORObject.ToString() method to turn the object into a string. If this CBORObject is from a third-party library, does the documentation state that ToString() will produce valid JSON? If so, then it definitely has a bug; it should be doing the proper escaping as required by the JSON spec. If there is no such promise of valid JSON, then you can't expect that Json.Net will be able to parse the string, even if it sort of looks like JSON. (You might check to see whether the CBORObject has some other dedicated method like ToJson() for performing this conversion.) If CBORObject is your own code, then it is on you to escape the strings properly when converting from CBOR to JSON.

How automatic escape quotes in json (C#)

From server I get json. Json is very big. I show litle piece of this
{
"id": "9429531978965160",
"name": "Morning in "Paris"", // json.net cannot deserialize this line, because line have no escaped quotes.
"alias": "ThisAlias"
}
The problem is the server side that generates invalid JSON.
You could try writing a regex that fixes this (searches for any quotes in between the third and last). Just note that there might be many other issues with the JSON, like newlines that are not escaped etc.
It's not just that the output you are receiving is non-standard json, it's broken in such a way that it's not a well-defined language and doesn't parse unambiguously even in the simple cases. How should you parse {"a": "A", "b": "B"}? One way is as legal json. Another valid parse is a single property a with the value "A\", \"b\": \"B".
As others have said, the best resolution is to fix the server so that it no longer outputs invalid garbage. If that's not an option, you'll have to write your own parser. A normal parser would declare an syntax error at the 'P' in "Paris". Your parser could back up to the last quote token and try to treat it as if it were escaped. The next syntax error is at the second of the consecutive quotes, and again it could back up and treat the quote token as if it were escaped. If there are any other ways in which the input deviates from legal json you'll need to handle those as well.
If you're not familiar with parsers, this will take a while. And when you're done you'll have a parser that recognizes a poorly-specified and almost totally useless language, which is to say that it will largely be a waste of time. Do what you can to fix it on the server side.

Extracting JSON from JSONP

I am parsing a JSON file using C#. Here is what I got from the server:
loadData([
{"id":"id1","nm":"name1"},
{"id":"id2","nm":"name2"},
{"id":"id3","nm":"name3"}
]);
This is not the entire string, as I have deleted some of the values to make it appear more straightforward.
As you can see, this JSON is not parseable because it ends with semicolon (;) and has a bunch of other issues which need to be fixed.
Now that I have this data, is there any workaround I can do on the client side to parse this JSON?
The server gave you more than the JSON file. It gave you loadData(jsonData); with jsonData looking like this :
[
{"id":"id1","nm":"name1"},
{"id":"id2","nm":"name2"},
{"id":"id3","nm":"name3"}
]
So you will have to parse this to extract the JSON file.

Restsharp parsing names not supported by C# Json

Hi I'm making a web api client that returns stuff in json.
I'm using Restsharp that uses newtonsoft.json to deserialize json objects.
The problem is that the server returns an object with a property with #Text as name. Is there a way to make restsharp parse this?
Here is a sample:
image: [
{
#text: http://userserve-ak.last.fm/serve/34s/55125087.png
size: small
}]
All the other properties are being parsed just right the only problem is this one, the property is a string type so no problem in here.
Regards
That JSON isn't valid; you need to put quotes around the #text key (so make it "#text") as well as both values (so "http://...png" and "small").

Categories