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?

2
  • Why not create a vector<Employee> and push_back to it? Commented Feb 2, 2014 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. Commented Feb 3, 2014 at 4:35

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.