I am using boost-property-tree in a C++ application, where I am trying to read a JSON file users.json
and store the data into a vector of object (std::vector<User> users;
).
The JSON file looks this this:
{
"OperatingSystem":"Windows 10",
"users" :
[
{
"firstName":"John",
"lastName":"Black"
},
{
"firstName":"Kate",
"lastName":"Red"
},
{
"firstName":"Robin",
"lastName":"White"
}
]
}
I have succedded reading the OperatingSystem
property with the following line of code:
boost::property_tree::ptree treeRoot;
boost::property_tree::read_json("users.json", treeRoot);
std::string operatingSystem = treeRoot.get<std::string>("OperatingSystem");
std::cout << "OS : " << operatingSystem << std::endl;
and that works fine.
In order to store the users, I have created a User class. You can see the header file User.hpp
below:
#ifndef USER_H
#define USER_H
#include <iostream>
#include <string>
class User
{
private:
// Properties
std::string firstName;
std::string lastName;
public:
// Constructors
User();
User(std::string firstName, std::string lastName);
// Getters
std::string getFirstName();
std::string getLastName();
// Setters
void getFirstName(std::string firstName);
void getLastName(std::string lastName);
};
#endif // USER_H
and the User.cpp
file here:
#include "User.hpp"
#include <iostream>
#include <string>
// Constructors
User::User()
{
this->firstName = "";
this->lastName = "";
}
User::User(std::string firstName, std::string lastName)
{
this->firstName = firstName;
this->lastName = lastName;
}
// Getters
std::string User::getFirstName()
{
return firstName;
}
std::string User::getLastName()
{
return lastName;
}
// Setters
void User::getFirstName(std::string firstName)
{
this->firstName = firstName;
}
void User::getLastName(std::string lastName)
{
this->lastName = lastName;
}
In my main.cpp
I am trying to load the users into a vector as such:
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "User.hpp"
int main(int argc, char **argv)
{
boost::property_tree::ptree treeRoot;
boost::property_tree::read_json("users.json", treeRoot);
std::vector<User> users;
users = treeRoot.get<std::vector<User>>("users");
return 0;
}
but it does not work.
In case someone knows how to read an array of objects from a JSON file via boost::property_tree::ptree
, please let me know.