Aviel Ovadiya
Aviel Ovadiya

Reputation: 21

How To Convert Vector To Json Object? C++

I Have A Vector Of RoomData Object Here Is The Object:

typedef struct RoomData
{
unsigned int id;
std::string name;
std::string maxPlayers;
unsigned int questionCount;
unsigned int timePerQuestion;
unsigned int isActive;
} RoomData;

I need to Convert this vector to json object. How can I do this? I Have no idea

Upvotes: 2

Views: 19133

Answers (3)

Daniel
Daniel

Reputation: 753

jsoncons and nlohmann both support conversion between JSON and C++ objects, as does Martin York's ThorsSerializer (see his answer.)

Given a vector of RoomData, viz.:

namespace ns {
    struct RoomData
    {
        unsigned int id;
        std::string name;
        std::string maxPlayers;
        unsigned int questionCount;
        unsigned int timePerQuestion;
        unsigned int isActive;
    } RoomData;
}

std::vector<ns::RoomData> rooms;
rooms.push_back(ns::RoomData{ 1, "Room 1", "Few", 2, 56, 1 });
rooms.push_back(ns::RoomData{ 2, "Room 2", "Lots", 2, 56, 1 });

Using jsoncons to convert to JSON and back:

#include <iostream>
#include <jsoncons/json.hpp>

namespace jc = jsoncons;

// Declare the traits. Specify which data members need to be serialized.
JSONCONS_ALL_MEMBER_TRAITS(ns::RoomData, id, name, maxPlayers, 
                           questionCount, timePerQuestion, isActive);

int main()
{
    std::vector<ns::RoomData> rooms;
    rooms.push_back(ns::RoomData{ 1, "Room 1", "Few", 2, 56, 1 });
    rooms.push_back(ns::RoomData{ 2, "Room 2", "Lots", 2, 56, 1 });

    std::string s;
    jc::encode_json(rooms, s, jc::indenting::indent);
    std::cout << "(1)\n" << s << "\n\n";

    auto rooms2 = jc::decode_json<std::vector<ns::RoomData>>(s);

    std::cout << "(2)\n";
    for (auto item : rooms2)
    {
        std::cout << "id: " << item.id << ", name: " << item.name 
                  << ", maxPlayers: " << item.maxPlayers << "\n"; 
    }
}

Output:

(1)
[
    {
        "id": 1,
        "isActive": 1,
        "maxPlayers": "Few",
        "name": "Room 1",
        "questionCount": 2,
        "timePerQuestion": 56
    },
    {
        "id": 2,
        "isActive": 1,
        "maxPlayers": "Lots",
        "name": "Room 2",
        "questionCount": 2,
        "timePerQuestion": 56
    }
]

(2)
id: 1, name: Room 1, maxPlayers: Few
id: 2, name: Room 2, maxPlayers: Lots

Using nlohmann to convert to JSON and back:

#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>

namespace nh = nlohmann;

// Provide from_json and to_json functions in the same namespace as your type   
namespace ns {
void from_json(const nh::json& j, ns::RoomData& val)
{
    j.at("id").get_to(val.id);
    j.at("name").get_to(val.name);
    j.at("maxPlayers").get_to(val.maxPlayers);
    j.at("questionCount").get_to(val.questionCount);
    j.at("timePerQuestion").get_to(val.timePerQuestion);
    j.at("isActive").get_to(val.isActive);
}

void to_json(nh::json& j, const ns::RoomData& val)
{
    j["id"] = val.id;
    j["name"] = val.name;
    j["maxPlayers"] = val.maxPlayers;
    j["questionCount"] = val.questionCount;
    j["timePerQuestion"] = val.timePerQuestion;
    j["isActive"] = val.isActive;
}
} // namespace ns

int main()
{
    std::vector<ns::RoomData> rooms;
    rooms.push_back(ns::RoomData{ 1, "Room 1", "Few", 2, 56, 1 });
    rooms.push_back(ns::RoomData{ 2, "Room 2", "Lots", 2, 56, 1 });

    std::stringstream ss;

    nh::json j = rooms;

    ss << std::setw(4) << j;

    std::cout << "(1)\n" << ss.str() << "\n\n";

    nh::json j2 = nh::json::parse(ss.str());
    auto rooms2 = j2.get<std::vector<ns::RoomData>>();

    std::cout << "(2)\n";
    for (auto item : rooms2)
    {
        std::cout << "id: " << item.id << ", name: " << item.name 
                  << ", maxPlayers: " << item.maxPlayers << "\n"; 
    }
}

Output:

(1)
[
    {
        "id": 1,
        "isActive": 1,
        "maxPlayers": "Few",
        "name": "Room 1",
        "questionCount": 2,
        "timePerQuestion": 56
    },
    {
        "id": 2,
        "isActive": 1,
        "maxPlayers": "Lots",
        "name": "Room 2",
        "questionCount": 2,
        "timePerQuestion": 56
    }
]

(2)
id: 1, name: Room 1, maxPlayers: Few
id: 2, name: Room 2, maxPlayers: Lots

Upvotes: 5

Loki Astari
Loki Astari

Reputation: 264401

Personally I like ThorsSerializer.

Serializing data is then trivial:

#include "ThorSerialize/JsonThor.h"
#include "ThorSerialize/SerUtil.h"
#include <iostream>
#include <string>

struct RoomData
{
    unsigned int id;
    std::string name;
    std::string maxPlayers;
    unsigned int questionCount;
    unsigned int timePerQuestion;
    unsigned int isActive;
};

ThorsAnvil_MakeTrait(RoomData, id, name, maxPlayers, questionCount, timePerQuestion, isActive);

Example Usage:

int main()
{
    using ThorsAnvil::Serialize::jsonImport;
    using ThorsAnvil::Serialize::jsonExport;

    RoomData    data{6, "Bed Room", "Lots of them", 2, 56, 1};

    std::cout << jsonExport(data) << "\n";
}

Output:

{
    "id": 6,
    "name": "Bed Room",
    "maxPlayers": "Lots of them",
    "questionCount": 2,
    "timePerQuestion": 56,
    "isActive": 1
}

Upvotes: 1

krisz
krisz

Reputation: 2695

You should use a json library. nlohmann/json is solid choice nowadays, but you can find a comparison by comformance and performance here.

Also you can omit the typedef in C++, it automatically creates one.

Upvotes: 0

Related Questions