Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rapidJSON adding an array of structs

I want to be able to create the following JSON output using rapidJSON

{
    "year": 2013,
    "league": "national",
    "teams": [
        {
            "teamname": "reds",
            "teamcity": "cincinnati",
            "roster": [
                {
                    "playername": "john",
                    "position": "catcher"
                },
                {
                    "playername": "joe",
                    "position": "pitcher"
                }
            ]
        }
    ]
}

This is valid JSON... Verified at JSONLint.com I know how to create a document and use AddMember to add "year" and "league".

I can not figure out and have not seen any examples of how to add an array that has a structure like "teams" or "roster"

How does one add "teams" which is an array of structures? Any help or point me to an example would be great.

like image 633
user2004460 Avatar asked Jan 23 '13 15:01

user2004460


2 Answers

Lets assume we have a std::vector roster containing PlayerName() and Postion() accessor functions on the Roster class that return std::string&.

rapidjson::Document jsonDoc;
jsonDoc.SetObject();
rapidjson::Value myArray(rapidjson::kArrayType);
rapidjson::Document::AllocatorType& allocator = jsonDoc.GetAllocator();

std::vector<Roster*>::iterator iter = roster.begin();
std::vector<Roster*>::iterator eiter = roster.end();
for (; iter != eiter; ++iter)
{
    rapidjson::Value objValue;
    objValue.SetObject();
    objValue.AddMember("playername", (*iter)->PlayerName().c_str(), allocator);
    objValue.AddMember("position", (*iter)->Position().c_str(), allocator);

    myArray.PushBack(objValue, allocator);
} 

jsonDoc.AddMember("array", myArray, allocator);
rapidjson::StringBuffer strbuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
jsonDoc.Accept(writer);

const char *jsonString = strbuf.GetString();  // to examine the encoding...

This will get you an array of structures in the document. All you should need to do to get the rest of the structure is to nest rapidjson objects within each other and use AddMember() to build your complex object tree. Hope this helps.

like image 73
CodeWhore Avatar answered Oct 02 '22 16:10

CodeWhore


In Vs2012/Rapidjson Version 0.1, following statement gets unreadable code when output document from StringBuffer.

objValue.AddMember("position", (*iter)->Position().c_str(), allocator);

after a few hours dig, i figured out how to do it in a correctly way.

Value tmp;
tmp.SetString( (*iter)->Position().c_str(), allocator);
objValue.AddMember("position", tmp, allocator);

here is a tutorial: http://miloyip.github.io/rapidjson/md_doc_tutorial.html

like image 41
alex.wang Avatar answered Oct 02 '22 15:10

alex.wang