I want to convert an array of unsigned short to JSON using the nlohmann library.
My variable type is a pointer to a null-terminated list of unsigned short. The typedef is this:
typedef unsigned short USHORT;
typedef USHORT * LPUSHORT;
I prepared this overload to conveniently process this type:
void to_json(nlohmann::json &resultJson, LPUSHORT lp)
{
while (*lp != NULL)
{
nlohmann::json single = (*lp);
resultJson["list"].push_back(single);
lp++;
}
}
But when doing this
resultJson["nids"] = (LPUSHORT) lp->nids;
I get the error:
no operator matches these operands
operand types are: nlohmann::json_abi_v3_11_2::basic_json<std::map, std::vector, std::string, bool, int64_t, uint64_t, double, std::allocator, nlohmann::json_abi_v3_11_2::adl_serializer, std::vector<uint8_t, std::allocator<uint8_t>>, void> = LPUSHORT
I also tried it with other typedefs, which are structs of short, int, char*,... all this works. But not directly when converting LPUSHORT.
I am not sure it will work, but try this (C++20 and onwards):
#include <algorithm>
#include <span>
auto past_the_end_elem = std::find(std::cbegin((LPUSHORT)lp->nids), std::cend((LPUSHORT)lp->nids), nullptr);
resultJson["nids"] = std::span<USHORT>(std::cbegin((LPUSHORT)lp->nids, past_the_end_elem);