node.js - 在 nodejs 中使用 Apache Thrift 进行序列化-反序列化

标签 node.js serialization deserialization thrift

我正在开发一个 Node.js 应用程序,我需要序列化和反序列化 .thrift 文件中定义的结构的实例,如下所示:

 struct Notification {
   1: string subject,
   2: string message
 }

根据 http://www.gettingcirrius.com/2011/03/rabbitmq-with-thrift-serialization.html 上的教程,这在 Java 中很容易实现:

    Notification notification = new Notification();
    TDeserializer deserializer = new TDeserializer();
    deserializer.deserialize(notification, serializedNotification);
    System.out.println("Received "+ notification.toString());

但我找不到如何使用 Thrift 的 nodejs 库完成此操作。请问有人可以帮忙吗?

最佳答案

好吧,在浪费了大量时间研究和尝试不同的解决方案之后,我终于找到了我自己问题的答案:

//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);

通知是我希望序列化的对象。此时,可以在 transport.outBuffers 字段中找到字节数组: var byteArray = transport.outBuffers;

对于反序列化:

var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);

假设已将以下行添加到 thrift 的 nodejs 库的 index.js 文件中:

exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;

关于node.js - 在 nodejs 中使用 Apache Thrift 进行序列化-反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13310451/

相关文章:

json - 使用 Serde 将两种类型转换为一种类型

java - 带有子对象的 pojo 的 JSON 序列化

java - FindBugs 希望 readObject(...) 为序列化私有(private),为什么?

node.js - 使用 Nodejs 和 Mongodb 访问 EJS 文件中 App.js 中声明的函数

node.js - 无法让 TypeScript 监视我的项目和 nodemon 重新加载它

c# - 如何使用 .NET 运行时序列化识别放置在独立存储中的对象的版本?

c++ - 在 C# 中反序列化在 C++ 中序列化的字节数组

scala - 使用 Scala 应用程序将 List[Object] 转换为案例类

javascript - Jade 模板 - 动态调用 Mixin

javascript - Node.js 中用于缓冲图像的 RGB 数组