Example: serialization_json_example
Serializes MRPT objects to and from JSON with mrpt::serialization::CSchemeArchive.
Example console output:
{ "pose_pdf": { "datatype": "mrpt::poses::CPosePDFGaussian", "version": 1, "mean": { "datatype": "mrpt::poses::CPose2D", "version": 1, "x": 1.0, "y": 2.0, "phi": 1.5707963267948966 }, "cov": { "datatype": "mrpt::math::CMatrixD", "version": 1, "nrows": 3, "ncols": 3, "data": "[0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 ;0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 ;0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 ]" } }, "pose": { "datatype": "mrpt::poses::CPose2D", "version": 1, "x": 5.0, "y": 6.0, "phi": 0.0 } } read pose:[5.000000 6.000000 0.000000deg]
Modules: mrpt_poses, mrpt_serialization
C++ example source code:
/* _ | | Mobile Robot Programming Toolkit (MRPT) _ __ ___ _ __ _ __ | |_ | '_ ` _ \| '__| '_ \| __| https://www.mrpt.org/ | | | | | | | | |_) | |_ |_| |_| |_|_| | .__/ \__| https://github.com/MRPT/mrpt/ | | |_| Copyright (c) 2005-2026, Individual contributors, see AUTHORS file See: https://www.mrpt.org/Authors - All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include <iostream> // cout #include <sstream> // stringstream #include <mrpt/poses/CPosePDFGaussian.h> #include <mrpt/serialization/CSchemeArchive.h> #include <iostream> // cout void WriteAndReadExample() { // Define the MRPT objects to be serialized: mrpt::poses::CPosePDFGaussian pdf1{ mrpt::poses::CPose2D{1.0, 2.0, mrpt::DEG2RAD(90.0)}, mrpt::math::CMatrixDouble33() }; mrpt::poses::CPose2D p1{5.0, 6.0, mrpt::DEG2RAD(.0)}; // -------------------- // JSON Serialization // -------------------- // Create a JSON archive: auto arch = mrpt::serialization::archiveJSON(); // Writes the objects to the JSON archive: arch["pose_pdf"] = pdf1; arch["pose"] = p1; // Writes the JSON representation to an std::ostream std::stringstream ss; ss << arch; // also, print to cout for illustration purposes: std::cout << arch << "\n"; // -------------------- // JSON Deserialization // -------------------- // rewind stream for reading from the start ss.seekg(0); // Create a new JSON archive for reading auto arch2 = mrpt::serialization::archiveJSON(); // Load the plain text representation into the archive: ss >> arch2; // Parse the JSON data into an MRPT object: mrpt::poses::CPosePDFGaussian pdf2; arch2["pose_pdf"].readTo(pdf2); mrpt::poses::CPose2D p2; arch2["pose"].readTo(p2); std::cout << "read pose:" << p2.asString() << "\n"; } int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { try { WriteAndReadExample(); return 0; } catch (const std::exception& e) { std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << "\n"; return -1; } catch (...) { printf("Untyped exception!"); return -1; } }