简体   繁体   English

如何检查json是否可以解析数据

[英]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解析器中引发异常而崩溃

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. 如果使用jQuery,则可以使用parseJSON函数测试数据,然后再将其发送到服务器。

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

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

Just try to url_encode the message you sending. 只需尝试对发送的邮件进行url_encode。 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. 或者使用您自己的算法对该消息进行编码,该算法将用其十六进制表示形式替换每个消息符号(例如“ Hello!”->“ 48656c6c6f21”),但是消息大小将加倍。 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. 然后,如果您使用自己的编码方法,则必须在服务器端对消息进行解码,将自动对url_encoded数据进行解码。 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 最后,要测试字符串中无效字符的字符串,请遍历字符串char并进行测试,它们是否包含在不允许的字符字符串中,例如

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 PS我不是英语母语人士,并且与Objective C并不相同,所以不要对我有太多的判断:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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