跨語言對象序列化:MGen

jopen 9年前發布 | 17K 次閱讀 MGen

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.baiduhome.net/lib/view/home/1419161853308

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!