简体   繁体   中英

How to check whether json can parse the data

I am sending a message with special characters to the server, since server cannot handle special characters it is replying with

</style>
</head>
<body>
    <div id="content">
        <h1>An Error Was Encountered</h1>
        <p>The URI you submitted has disallowed characters.</p> </div>
</body>
</html>

And my app is crashing by throwing exception in JSON parser

JSON_FAIL(JSON_TEXT("Not JSON!"));
throw std::invalid_argument(EMPTY_STRING2);

Is it possible to check whether the message is valid or not before sending request to server.So i can put alert "not valid message" to the user or any other way to parse the error message("An Error Was Encountere") and displaying alert before parsing.

由于它引发了异常...我只是将parse方法放在try块中,并在catch块中显示了警报。

If using jQuery, you can use the parseJSON function to test the data before it's sent to the server.

var obj = jQuery.parseJSON('{"name":"John"}');<br/>
alert( obj.name === "John" );

http://api.jquery.com/jQuery.parseJSON/

Just try to url_encode the message you sending. Or encode that message with your own algorithm, which will replace each message symbol with its hex representation (like "Hello!" -> "48656c6c6f21"), but the message size will be doubled. Then you must decode the message at the server side if you use your own method of encoding, url_encoded data will be decoded automaticaly. Also you MUST check response text before trying to parse it. Simply check does it beginning with "" text. And finally, to test string for invalid characters loop thru string chars and test, does they contained in string of disallowed characters, smth like

array<Byte> strchars = new array<Byte>(255);
str.GetBytes(strchars, 0, str.length);
string dch = "<>@#%^&`\\'\"";
bool invalid = false;
for (i=0;i<str.length;i++) if (dch.IndexOf(strchars[i]) >= 0) {invalid = true; break; }

PS I'm not native english speaker, and uncommon with Objective C, so don't judge me a lot :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM