文件API - Blob到JSON [英] File API - Blob to JSON

查看:184
本文介绍了文件API - Blob到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML5,WebSocket和File API进行一些实验。
我正在使用Tomcat7 WebSocket实现。
我能够从servlet发送和接收短信。我现在要做的是从servlet发送到客户端JSON对象,但我想避免文本消息,以便跳过客户端上的JSON.parse(或类似),所以我试图发送二进制消息。
servlet部分非常简单:

I'm trying to do some experiment with HTML5, WebSocket and File API. I'm using the Tomcat7 WebSocket implementation. I'm able to send and received text messages from the servlet. What I want to do now is to send from the servlet to the client JSON objects, but I want to avoid text message in order to skip the JSON.parse (or similar) on the client, so I'm trying to send binary messages. The servlet part is really simple:

String s = "{arr : [1,2]}";
CharBuffer cbuf = CharBuffer.wrap(s);      
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();      
getWsOutbound().writeBinaryMessage(encoder.encode(cbuf));
getWsOutbound().flush();

在此消息之后,在客户端上我看到我收到了一个二进制帧,转换为Blob对象( http://www.w3.org/TR/FileAPI/#dfn-斑点)。
问题是:是否可以从Blob获取JSON对象?
我查看了FileReader界面( http://www.w3 .org / TR / FileAPI / #FileReader-interface ),我使用这样的代码来检查FileReader可以做什么(第一行创建一个全新的Blob,所以如果你想要你可以动态测试):

After this message, on the client I see that I received a binary frame, that is converted to a Blob object (http://www.w3.org/TR/FileAPI/#dfn-Blob). The question is: is it possible to get the JSON object from the Blob? I took a look at the FileReader interface (http://www.w3.org/TR/FileAPI/#FileReader-interface), and I used code like this to inspect what the FileReader can do (the first line creates a brand new Blob, so you can test on the fly if you want):

var b = new Blob([{"test": "toast"}], {type : "application/json"});
var fr = new FileReader();
fr.onload = function(evt) {
    var res = evt.target.result;
    console.log("onload",arguments, res, typeof res);
};
fr.readAsArrayBuffer(b);

使用我在File Reader实现中看到的所有readAs ...方法(我' m使用Chrome 22)。无论如何,我没有找到有用的东西。

using all the "readAs..." methods that I saw on the File Reader implementation (I'm using Chrome 22). Anyway I didn't find something useful.

你有什么建议吗?谢谢。

Did you have any suggestion? Thanks.

推荐答案

你所做的事情在概念上是错误的。 JSON是对象的字符串表示形式,而不是对象本身。因此,当您通过线路发送JSON的二进制表示时,您将发送该字符串的二进制表示。没有办法在客户端解析JSON以将JSON字符串转换为JavaScript对象。

What you're doing is conceptually wrong. JSON is a string representation of an object, not an object itself. So, when you send a binary representation of JSON over the wire, you're sending a binary representation of the string. There's no way to get around parsing JSON on the client side to convert a JSON string to a JavaScript Object.

您绝对应该始终将JSON作为文本发送到客户端,并且你应该总是调用JSON.parse。没有别的事情对你来说很容易。

You absolutely should always send JSON as text to the client, and you should always call JSON.parse. Nothing else is going to be easy for you.

这篇关于文件API - Blob到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆