Created
September 22, 2021 01:58
-
-
Save vvrs/0554258b32325728370c52d3323b4bc1 to your computer and use it in GitHub Desktop.
Serialize and deserialize Eigen Matrix using jsoncpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <string> | |
#include <Eigen/Core> | |
#include <vector> | |
#include <memory> | |
#include "json/json.h" | |
template<typename EigenType> | |
Json::Value toJSON(const std::string& name, const Eigen::PlainObjectBase<EigenType>& mat) | |
{ | |
Json::Value traj; | |
traj["rows"] = mat.rows(); | |
traj["cols"] = mat.cols(); | |
const std::size_t size = mat.size() * sizeof(typename EigenType::Scalar); | |
std::vector<double> vec(mat.data(), mat.data() + mat.rows() * mat.cols()); | |
Json::Value v; | |
for (auto&& element: vec) { | |
v.append(element); | |
} | |
traj["data"] = v; | |
Json::Value root; | |
root[name] = traj; | |
return root; | |
} | |
Eigen::MatrixXd toEigen(Json::Value jv) | |
{ | |
Eigen::MatrixXd ret; | |
int rows = jv["rows"].asInt(); | |
int cols = jv["cols"].asInt(); | |
Json::Value data = jv["data"]; | |
Eigen::MatrixXd a; | |
a.resize(rows, cols); | |
for(int i=0; i<rows; ++i) | |
{ | |
for(int j=0; j<cols; ++j) | |
{ | |
a(i,j) = data[i + j*rows].asDouble(); | |
} | |
} | |
return a; | |
} | |
Json::Value read4mJson(std::string strr) | |
{ | |
std::stringstream ss; | |
ss << strr; | |
Json::Value root; | |
Json::CharReaderBuilder builder; | |
builder["collectComments"] = true; | |
JSONCPP_STRING errs; | |
if(!parseFromStream(builder, ss, &root, &errs)) | |
{ | |
std::cout << errs << std::endl; | |
return EXIT_FAILURE; | |
} | |
return root; | |
} | |
int main() { | |
Eigen::MatrixXd a(3,4); | |
a << 1,2,3,4,5,6,7,8,-1,-2,-3,-4; | |
std::cout << "Matrix to serialize : \n"<< a << std::endl; | |
Json::Value jv = toJSON("mat", a); | |
Json::StreamWriterBuilder builder; | |
const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); | |
std::stringstream ss; | |
writer->write(jv, &ss); | |
Json::Value rv = read4mJson(ss.str()); | |
Eigen::MatrixXd k = toEigen(rv["mat"]); | |
std::cout << "De-serialized matrix : \n"<< k << std::endl; | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://godbolt.org/z/zc3faePPY