Question

I'm using libJson (C++ library) for parsing a JSON file. My JSON files looks as follows.

{
    "Comany": 
    {
        "name": "Some Company",
        "Resources": {
            "employees": [
                {"name": "John", "id": "23432"}, 
                {"name": "Alex", "id": "32432"}
            ], 
            "Computers": [
                {"IPAddress": "192.168.1.3", "CPU": "IntelCorei5"},
                {"IPAddress": "192.168.1.4", "CPU": "IntelCorei3"}
            ]
        }  
    }
}

I have structs for Employee and Computer. I would like to create an array of structures.

Any ideas how this can be done with libJson?

Was it helpful?

Solution

Pakal Persist looks like a perfect fit for what you are trying to do.

since there is no reflection in c++ the only extra thing you have to do is to add a member function.

#include "JsonReader.h"

struct Computer
{
    std::string IPAddress;
    std::string CPU;

    void persist(Archive* archive)
    {
        a->value("IPAddress",IPAddress);
        a->value("CPU",CPU);
    }
}   

struct Employee
{
    std::string name;
    int id;

    void persist(Archive* archive)
    {
        a->value("name",name);
        a->value("id",id);
    }
}


struct Resources
{
    std::vector<Employee> employees;
    std::vector<Computer*> Computers;

    void persist(Archive* archive)
    {
        archive->value("employees","employee",employees);
        archive->value("Computers","computer",Computers);
    }
}

struct Company
{
    std::string name;
    Resources resources;

    void persist(Archive* a)
    {
        a->value("name",name);
        a->value("Resources",resources);
    }
}



Company company;

JsonReader reader;
reader.read("company.json","Company",company);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top