开发者

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>
        &开发者_如何学JAVAlt;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.


Since it was throwing an exception... I just put the parse method in try block and in the catch block I displayed an alert.


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; }

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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜