这是一个老问题,但经常出现。我会使用https://github.com/beached/daw_json_link,然后使用以下C++数据结构
struct links_element_t {
std::string href;
std::string method;
std::string rel;
std::string type;
};
struct json_object_t {
std::string name;
std::string city;
std::vector<links_element_t> links;
};
为了从JSON文档中进行映射,需要使用以下代码。
#include <daw/daw_json_link.h>
namespace daw::json {
template <>
struct json_data_contract<links_element_t> {
static constexpr char const mem_href[] = "href";
static constexpr char const mem_method[] = "method";
static constexpr char const mem_rel[] = "rel";
static constexpr char const mem_type[] = "type";
using type = json_member_list<json_string<mem_href>, json_string<mem_method>,
json_string<mem_rel>, json_string<mem_type>>;
static inline auto to_json_data(links_element_t const& value) {
return std::forward_as_tuple(value.href, value.method, value.rel,
value.type);
}
};
template <>
struct json_data_contract<root_object_t> {
static constexpr char const mem_name[] = "name";
static constexpr char const mem_city[] = "city";
static constexpr char const mem_links[] = "links";
using type = json_member_list<
json_string<mem_name>, json_string<mem_city>,
json_array<mem_links, json_class<no_name, links_element_t>,
std::vector<links_element_t>>>;
static inline auto to_json_data(root_object_t const& value) {
return std::forward_as_tuple(value.name, value.city, value.links);
}
};
}
接下来,将其解析为json_object_t
的方法如下:
json_object_t json_object = daw::json::from_json<json_object_t>( json_doc );