vectorXd from_json?

问题描述

我正在尝试使用eigen :: VectorXd和nlohmann-json库实现类的json序列化。将类存储为JSON字符串不是问题。如何从JSON解析VectorXd?还有其他更适合此任务的库吗?

#include "json.hpp"

class TransformationStep {
public:
  VectorXd support_vector;
  int number;

  TransformationStep(int number_param,VectorXd support_vectorParam) {
    number = number_param;
    support_vector = support_vectorParam;
  }

  ~TransformationStep() {
  }

  //json serialization
  void to_json(nlohmann::json &j);
  void from_json(const nlohmann::json &j);
};


void TransformationStep::to_json(nlohmann::json &j) {
  j["number"] = number;
  j["support_vector"] = support_vector;
}


void Ftf::from_json(const nlohmann::json &j)
{
    number = (j.at("number").get<int>());
    //support_vector = j["support_vector"].get<VectorXd>()); //???
}

------输出调用to_json(nlohmann :: json&j)------

{
  "number": 3,"support_vector": [
    -0.00036705693279489064,0.020505439899631835,0.3531380358938106,0.0017673029092790872,-0.9333248513057808,0.04670404618976708,-0.21905858722244081,-1.011945322347849,-0.09172040021815037,0.008526811888809391,0.05187648010664058
  ]
}

解决方法

我想出了

void vector_from_json(VectorXd& vector,const nlohmann::json &j) {
  vector.resize(j.size());
  size_t element_index=0;
  for (const auto& element : j) {
    vector(element_index++) = (double) element;
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...