libLicenseClient/api/JSONSerialization.h
2018-03-27 23:03:06 +02:00

119 lines
2.8 KiB
C++

#pragma once
#include <boost/property_tree/ptree.hpp>
#include <map>
#include <ostream>
#include <set>
#include <string>
#include <vector>
void serialize(std::ostream& os, const std::string& str);
template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
void serialize(std::ostream& os, T intVal)
{
os << intVal;
}
template <typename T>
void serialize(std::ostream& os, const std::vector<T>& vec)
{
os << "[";
if (vec.size() > 0)
{
serialize(os, vec[0]);
std::for_each(std::begin(vec) + 1, std::end(vec), [&os](const auto& el)
{
os << ',';
serialize(os, el);
});
}
os << "]";
}
template <typename T>
void serialize(std::ostream& os, const std::set<T>& setVal)
{
bool first = true;
os << "[";
std::for_each(std::begin(setVal), std::end(setVal), [&os, &first](const auto& el)
{
if (!first)
{
os << ',';
}
serialize(os, el);
first = false;
});
os << "]";
}
template <typename T>
void serialize(std::ostream& os, const std::map<std::string, T>& m)
{
bool first = true;
os << "{";
std::for_each(std::begin(m), std::end(m), [&os, &first](const auto& pair)
{
if (!first)
{
os << ',';
}
serialize(os, pair.first);
os << ':';
serialize(os, pair.second);
first = false;
});
os << "}";
}
void deserialize(const boost::property_tree::ptree& tree, std::string& stringVal);
template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
void deserialize(const boost::property_tree::ptree & tree, T& intVal)
{
intVal = tree.get_value<T>();
}
template <typename T>
void deserialize(const boost::property_tree::ptree& tree, std::vector<T>& vec)
{
vec.clear();
for (const boost::property_tree::ptree::value_type &el : tree)
{
// el.first contain the string "" if it was JSON array
T val;
deserialize(el.second, val);
vec.push_back(std::move(val));
}
}
template <typename T>
void deserialize(const boost::property_tree::ptree& tree, std::set<T>& setVal)
{
setVal.clear();
for (const boost::property_tree::ptree::value_type &el : tree)
{
// el.first contain the string "" if it was JSON array
T val;
deserialize(el.second, val);
setVal.insert(std::move(val));
}
}
template <typename T>
void deserialize(const boost::property_tree::ptree& tree, std::map<std::string, T>& mapVal)
{
mapVal.clear();
for (const boost::property_tree::ptree::value_type &el : tree)
{
std::string key;
T val;
key = el.first;
deserialize(el.second, val);
mapVal.insert(std::make_pair(std::move(key), std::move(val)));
}
}