jeudi 10 mars 2022

nlohmann json parsing key and value to a class

I have the following data structure

{
   "France": {
      "capital": "paris",
      "highpoint": "20",
    },
   "Germany": {
      "size": "20",
      "population": "5000"
    }
}

I am using nlohmann json to parse it

I need to parse it into a country class

country.h

class Country {
public:
  friend void to_json(json &j , const Country &c);
  friend void from_json(const json &j , Country &c); 
private:
  std::string _name; 
  std::map _detail; 

to_json and from json implementation

  to_json(json &j, const Country &c) {
    j = json;

  void from_json(const json& j, Item& cat){
    auto c = j.get<std::map<std::string, std::map<std::string, std::string>>>();
    cat._id = c.begin()->first;
    cat._entry = c.begin()->second;

when i try to get the country from the json it does not work like this

  std::ifstream in("pretty.json");
  json j = json::parse(in);
  Country myCountry = j.get<Country>(); 

I have looked at the documentation the only i see to create the from_json is by knowing the key before hand see doc

j.at("the_key_name").get_to(country._name);

is there a way i could parse it without knowing the key ? in the from_json method ?

Aucun commentaire:

Enregistrer un commentaire