How can we serialize std::complex
And vector
I make to_json/from_json functions, but I wonder if there is a better way.
std::complex is not supported out of the box. So, yes, you need to define to_json/from_json functions. There, you need to define how you want to represent the values.
Specifically, you need to define them for std::complex. If you do that, then std::vector<std::complex> comes for free.
thx for your replies,
I can't make it work for free with vector ;)
can you post a sample code?
How does your code for std::complex look like?
... It works when I put the code in std namespace... sorry
it could help:
namespace std {
template< class T > to_json(json &j, const std::complex< T > &p) {
j = json {to_string(p.real()) + "+i" + to_string(p.imag())};
}
template< class T > from_json(const json &j, std::complex< T > &p) {
}
}
...
vector<complex<float>> v = { {1,1}, {2,2}};
json j(v);
Do you have an efficient way to deserialize ;)
How about
#include "json.hpp"
#include <iostream>
#include <complex>
using json = nlohmann::json;
namespace std {
template< class T > void to_json(json &j, const std::complex< T > &p) {
j = json {p.real(), p.imag()};
}
template< class T > void from_json(const json &j, std::complex< T > &p) {
p.real(j.at(0));
p.imag(j.at(1));
}
}
int main() {
std::vector<std::complex<float>> v1 = { {1,2}, {3,4}};
json j(v1);
std::cout << j << std::endl;
auto v2 = j.get<std::vector<std::complex<float>>>();
std::cout << std::boolalpha << (v1 == v2) << std::endl;
}
ok tested and approved!
A big thank you ;)
You're welcome!