我已经使用 Java 编写了套接字通信服务器,并使用套接字连接编写了一个带有 AS3 的 AIR 程序。 通过套接字连接的通信是通过 JSON 序列化完成的。
有时在套接字上串起很长的 JSON,AS3 代码会提示存在 JSON 解析错误。
我以 end 字符串结尾的每个 JSON 字符串让程序知道,它不是消息的结尾,所以这不是 AIR 程序读取的问题部分消息。
该错误仅发生在非常长的json 字符串上,例如长度为78031 的字符串。 JSON 序列化有什么限制吗?
最佳答案
我遇到了同样的问题。问题出在 Flash 应用程序从套接字读取数据时。
要点是,即使服务器没有发送所有数据,Flash ProgressEvent.SOCKET_DATA 事件也会触发,并且会留下一些东西(尤其是当数据很大且连接很慢时)。 所以像 {"key":"value"} 这样的东西分为两个(或更多)部分,比如:{"key":"val 和 ue"。此外,有时您可能会在一条消息中收到多个连接的 JSON,例如 {"json1key":"value"}{"json2key":"value"} - 内置的 Flash JSON 解析器也无法处理这些。
为了解决这个问题,我建议您修改 Flash 应用程序中的 SocketData 处理程序,为接收到的字符串添加缓存。像这样:
// declaring vars
private var _socket:Socket;
private var _cache: String = "";
// adding EventListener
_socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
private function onSocketData(e: Event):void
{
// take the incoming data from socket
var fromServer: ByteArray = new ByteArray;
while (_socket.bytesAvailable)
{
_socket.readBytes(fromServer);
}
var receivedToString: String = fromServer.toString();
_cache += receivedToString;
if (receivedToString.length == 0) return; // nothing to parse
// convert that long string to the Vector of JSONs
// here is very small and not fail-safe alghoritm of detecting separate JSONs in one long String
var jsonPart: String = "";
var jsonVector: Vector.<String> = new Vector.<String>;
var bracketsCount: int = 0;
var endOfLastJson: int = 0;
for (var i: int = 0; i < _cache.length; i++)
{
if (_cache.charAt(i) == "{") bracketsCount += 1;
if (bracketsCount > 0) jsonPart = jsonPart.concat(_cache.charAt(i));
if (_cache.charAt(i) == "}")
{
bracketsCount -= 1;
if (bracketsCount == 0)
{
jsonVector.push(jsonPart);
jsonPart = "";
endOfLastJson = i;
}
}
}
// removing part that isn't needed anymore
if (jsonVector.length > 0)
{
_cache = _cache.substr(endOfLastJson + 1);
}
for each (var part: String in jsonVector)
{
trace("RECEIVED: " + part); // voila! here is the full received JSON
}
}
关于java - 最大 as3 adobe JSON 字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18211368/