跨语言对象序列化:MGen

jopen 9年前

MGen 是一个支持跨语言的对象序列化项目,由以下两部分组成:

  • 源码生成的工具 ( MGen 编译器 )

  • 语言的支持库

MGen 类似 Gooogle 的 Protocol Buffers ,可序列化到 JSON 和二进制格式。

目前支持的语言有:

  • C++

  • Java

  • JavaScript

示例代码:

#include <com/fruitcompany/ClassRegistry.h>  #include <mgen/serialization/JsonPrettyWriter.h>  #include <mgen/serialization/JsonReader.h>     using namespace mgen;  using namespace com::fruitcompany;  using namespace com::fruitcompany::fruits;     // A class registry for type identification  const ClassRegistry registry;     std::string toJSON(const MGenBase& object) {       // Create a target to stream the object to    std::stringstream stream;       // Create a writer object    JsonPrettyWriter<std::stringstream, ClassRegistry> writer(stream, registry);       // Write the object    writer.writeObject(object);       // Return the written string    return stream.str();  }     template <typename T>  T fromJSON(const std::string& json) {       // Create a data source to stream objects from    std::stringstream stream(json);       // Create a reader object    JsonReader<std::stringstream, ClassRegistry> reader(stream, registry);       // Read object. You can read T* polymorphicly with reader.readObject<T>()    return reader.readStatic<T>();  }     int main() {       // Create some objects    const Apple apple(Brand_A, 4);    const Banana banana = Banana().setLength(5).setBrand(Brand_B);       // Serialize them to JSON and print them    std::cout << toJSON(banana) << std::endl;    std::cout << toJSON(apple) << std::endl;       // Read the objects back from their serialized form    const Apple appleBack = fromJSON<Apple>(toJSON(apple));    const Banana bananaBack = fromJSON<Banana>(toJSON(banana));       // Check that they are still the same    std::cout << (apple == appleBack) << std::endl;    std::cout << (banana == bananaBack) << std::endl;       return 0;  }

项目主页:http://www.open-open.com/lib/view/home/1419161853308