Javascript deserializer not working for special characters - json

I am trying to desearilize a object as given below ,one of the string having some special characters associated with it and facing some errors.
obj= JsonConvert.DeserializeObject<response>(request.Message)
one of the input string looks like below
"Message":"{
'Id':'text me on dec may\' 17',
}"
Error details:After parsing a value an unexpected character was
encountered: 1. Path 'Id', line 4, position 56
thanks in advance

In my prior comment, I had mis-read the initial problem. Sorry about that.
In JavaScript I can do this:
JSON.parse('{"Message":"{\'Id\':\'text me on dec may\' 17\',}"}')
Which works just fine. Notice that I had to also escape the single quotes surrounding the inner string.

I have found the issue, actually it is problem with the input, after data serialization input should be appended with 2 backslash for each special characters, as when catching the data in API method, one of the backslash will be removed during data assigned(get/set) to the property.so if two slashes are there one will remove and another will use for deserailise the data.
Message":"{
'Id':'text me on dec may\' 17',
}"
thanks all for you support

Related

How to find JSON parse error in existing Ruby code

First let me say that while I am a programmer, Ruby is very new to me. I'm trying to fix an application created by another developer, but I cannot find the issue. When the code is run, I get the error below:
JSON::ParserError: unexpected token at '{
"account":"xxxxxxx",
"role":"3",
"email":"xxxx#xxxxxxxx.com",
"password":'xxxxxxxxxxxx',
"connect_host":"xxxxxxx.xxxxxxx.api.xxxxxxxx.com"
}
'
Account is numeric. Email is standard/no special characters. Password does have special characters, on of them being a double quote which is why it is wrapped in single quotes. Connect host is just an URL with alpha-numeric characters. I've Googled quite a bit but the results I've come up with dealt with people trying to escape certain characters. My hope is that another set of eyes can see what mine are missing.
Based on the JSON you've pasted in above the error is the usage of single quotes for the value of "password" which is 'xxxxxxxxxxxx'.
It needs to be in double quotes so change it to be:
"password":"xxxxxxxxxxxx",
If you control the code that sets the input go change that otherwise you will have to handle changing the single quote usage possibly through this answer (which is JS but demonstrates the concept), Parsing string as JSON with single quotes?

Why this Arduino sscanf JSON parsing problem?

I am trying to parse this JSON string:
{"FN":"142","SName":"stil.mp3","InPlaylist1":"1","InPlaylist2":"1","error":0}
I use this sscan statement:
' RetScanf = sscanf(OneJsonStr, "{\"FN\":\"%d\",\"SName\":\"%[^\"],\"InPlaylist1\":\"%d\",\"InPlaylist2\":\"%d\",\"error\":%d}", &Parameter1_FNo, Parameter2_FName, InP1, InP2, &err); '
but in only parses the two first parameter "FN" and "SName". any idea what I am doing wrong?
thnaks in advance
br.
Allan
In your sscanf() format, when matching the SName string, you never try to match the trailing double quote.
,\"SName\":\"%[^\"]\",
Also, since the format says that InP1/2 are integers, you should pass in their addresses (assuming they aren't already pointers).

Clojure: Escaping unicode `\U` in JSON encoding

Postamble for future readers
Elm allows literal C:\Users\myuser in strings
This is consistent with the JSON spec
My problem was unrelated to this, but several layers of escaping convoluted the problem. Future lesson: fully producing a minimal working example would have found the error!
Original question
I have a Clojure backend that talks to an Elm frontend. I hit a bump when decoding JSON values in Elm.
\U below means the literal characters backslash and U, as if read from a text file. "\\U" is the same string as input in Clojure and Elm source (\ must be escaped). Note enclosing "".
Problem: encoding \U
The literal string \U, escaped "\\U" is not accepted by the Elm string decoder.
A blog post suggests that to obtain the literal string \U, this should be encoded in source code as "\\\\U", "escaping the unicode escape".
The literal string I want to send to the client is C:\Users\myuser. I prefer to send valid JSON from the server to the client.
Clojure standard library behavior
clojure.data.json does not do anything special for strings containing the literal \U. The example below shows that \U and \m are threated equally, the backslash is escaped, and the following character ignored.
project.core> (clojure.data.json/write-str "C:\\Users\\myuser")
"\"C:\\\\Users\\\\myuser\""
Manual workaround
Temporary workaround is manually escaping the strings I need:
(defn escape-backslash-u [s]
(clojure.string/replace s "\\U" "\\\\U"))
Concrete questions
Is clojure.data.json/write-str behaving correctly? As I understand the documentation, output should be valid unicode.
Are other JSON libraries behaving similarly?
Is Elm's Json.Decode behaving correctly by rejecting the literal string \U?
Solution progress
A friendly Clojurians Slack user pointed to the JSON standard specification, specifically sections 7. Strings and 8.2. Unicode characters.
I think you may be on the wrong track here.
The string you gave as an example, "C:\\Users\\myuser" is completely unproblematic, it does not contain any Unicode escape sequences. It is a string containing the ASCII characters ‘C’, ‘:’, ‘\’, ‘U’, and so on. The backslash is the escape character in Clojure strings so it needs to be escaped itself to represent a literal backslash.
In any case the string "C:\\Users\\myuser" can be serialized with (clojure.data.json/write-str "C:\\Users\\myuser"), and, as you know, this gives "\"C:\\\\Users\\\\myuser\"". All of this seems perfectly straightforward and sound.
Printing "\"C:\\\\Users\\\\myuser\"" results in the original string "C:\\Users\\myuser" being printed. That string is accepted as valid by JSONLint, again as expected.
I understood it as Elm beeing unable to decode \"C:\\\\User... to "C:\\User... because it interprets \u as start for an escape sequence.
I tried elm here with the following code:
import Html exposing (text)
main =
text "\"c:\\\\user\\\\foo\"" // from clojure.data.json/write-str
which in turn compiles/runs to
"c:\\user\\foo"
which looks fine to me.
Are you sure there is nothing else going on (middleware, transport) ?

what is wrong with my JSON structure?

{"Street":
[
{
"Street_name":"Dewlane Dr",
"Street_numbers":
[
{
"number":26,
"Unit_number":""
}
]
}
]
}
but i get this error while parsing it on iPhone thorough SBJSON.
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: Street\" UserInfo=0x595fd60 {NSUnderlyingError=0x593cfc0
There's an extra closing quote after "Unit_number". Ah, that was just a copy-and-paste error.
There's nothing wrong with it, as far as I can see and according to jsonlint.com.
Just to break it down: Your structure has one outermost object, which has a Street property. The Street property's value is an array with one entry. That one entry is an object with the properties Street_name, which has a string value, and Street_numbers, which has an array value. The one entry in the Street_numbers array is an object with two properties, number and Unit_number.
Update: I never addressed the SBJSON error.
If you're getting that error from SBJSON, it suggests one of the following:
What you're feeding into SBJSON isn't what you've quoted (it's quite an easy mistake to make). For instance, perhaps what you're feeding in has gotten truncated in some way just after "Street":.
You have a character after "Street": looks like whitespace by the time you've pasted it into StackOverflow, but isn't whitespace by the usual definitions, and so SBJSON thinks it's a character that should be processed and is choking on it.
SBJSON has a bug in it related to the value being on the line following the colon (which seems unlikely).
SBJSON has a bug related to the precise kind of whitespace you have at that location. There are lots of different whitespace charactesrs in Unicode, if you've (probably inadvertently) used an unusual one, SBJSON may not be handling it correctly.
But if what looks like whitespace in what you posted is comprised entirely of carriage returns, spaces, tabs, line feeds, and other classic whitespace, and if the string you're passing to SBJSON's deserializer is what you've posted, it's a problem with SBJSON.

JSON and escaping characters

I have a string which gets serialized to JSON in Javascript, and then deserialized to Java.
It looks like if the string contains a degree symbol, then I get a problem.
I could use some help in figuring out who to blame:
is it the Spidermonkey 1.8 implementation? (this has a JSON implementation built-in)
is it Google gson?
is it me for not doing something properly?
Here's what happens in JSDB:
js>s='15\u00f8C'
15°C
js>JSON.stringify(s)
"15°C"
I would have expected "15\u00f8C' which leads me to believe that Spidermonkey's JSON implementation isn't doing the right thing... except that the JSON homepage's syntax description (is that the spec?) says that a char can be
any-Unicode-character-
except-"-or-\-or-
control-character"
so maybe it passes the string along as-is without encoding it as \u00f8... in which case I would think the problem is with the gson library.
Can anyone help?
I suppose my workaround is to use either a different JSON library, or manually escape strings myself after calling JSON.stringify() -- but if this is a bug then I'd like to file a bug report.
This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:
2.5. Strings
The representation of strings is
similar to conventions used in the C
family of programming languages. A
string begins and ends with quotation
marks. All Unicode characters may be
placed within the quotation marks
except for the characters that must be
escaped: quotation mark, reverse
solidus, and the control characters
(U+0000 through U+001F).
Any character may be escaped.
Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).
It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3◄
js>JSON_stringify(s, true)
"15°C 3◄"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.