0

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?

voodooattack
  • 1,127
  • 9
  • 16
Naresh
  • 633
  • 1
  • 6
  • 17
  • Why not create a `vector` and push_back to it? – Adam Feb 02 '14 at 18:50
  • my question was to know how an array can be read from JSON string using libJson (not to know how an array of structures can be created). I found json-c lib as better option this. – Naresh Feb 03 '14 at 04:35

1 Answers1

1

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);
elios264
  • 384
  • 4
  • 19