-
Hello This is the complement for the question How do I create a json object from an array of structs? But in this case, what I need to know is how to do the opposite, this is, fill the structs array from a JSON object. I have the following JSON: {
"array" : [
{
"a" : 1,
"c": true,
"d":"One",
"e":1.10
},
{
"a" : 2,
"c": false,
"d":"Two",
"e":2.20
},
{
"a" : 3,
"c": true,
"d":"Three",
"e":3.30
}
]
} And I'm trying to fill the #include <iostream>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
typedef struct
{
uint8_t a;
bool c;
string d;
float e;
} my_struct_t;
void to_json(json& j, const my_struct_t& ms)
{
j["a"] = ms.a;
j["c"] = ms.c;
j["d"] = ms.d;
j["e"] = ms.e;
}
void from_json(const json& j, my_struct_t& ms)
{
j.at("a").get_to(ms.a);
j.at("c").get_to(ms.c);
j.at("d").get_to(ms.d);
j.at("e").get_to(ms.e);
}
int main()
{
my_struct_t struct_array[] = {
{1, true, "One", 1.10},
{2, false, "Two", 2.20},
{3, true, "Three", 3.30}
};
json result = { {"array", struct_array} };
cout << result << endl;
auto JSON = result.get<my_struct_t>();
return 0;
} The output from
But I'm getting an exception on |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
First, the library will not be able to create a C-style array for you. You will only be able to retrieve a auto JSON = result["array"].get<std::vector<my_struct_t>>(); |
Beta Was this translation helpful? Give feedback.
First, the library will not be able to create a C-style array for you. You will only be able to retrieve a
std::vector
, though. For this, you need to "unpack" the JSON array from the JSON object like this: