rapidJSON添加一个结构数组

use*_*460 12 arrays json struct

我希望能够使用rapidJSON创建以下JSON输出

{
    "year": 2013,
    "league": "national",
    "teams": [
        {
            "teamname": "reds",
            "teamcity": "cincinnati",
            "roster": [
                {
                    "playername": "john",
                    "position": "catcher"
                },
                {
                    "playername": "joe",
                    "position": "pitcher"
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是有效的JSON ...在JSONLint.com上验证我知道如何创建文档并使用AddMember添加"年份"和"联盟".

我无法弄清楚并且没有看到任何关于如何添加具有"团队"或"名册"结构的数组的示例

如何添加"团队",这是一组结构?任何帮助或指向我的例子都会很棒.

Cod*_*ore 49

让我们假设我们有一个std :: vector名单,其中包含返回std :: string&的Roster类上的PlayerName()和Postion()访​​问器函数.

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...
Run Code Online (Sandbox Code Playgroud)

这将为您提供文档中的一系列结构.要获得结构的其余部分,您需要做的就是将rapidjson对象嵌套在彼此中,并使用AddMember()来构建复杂的对象树.希望这可以帮助.

  • 好一个!不幸的是,用户没有接受你的回答,无论如何你做了我的一天!:) (2认同)

小智 10

在Vs2012/Rapidjson Version 0.1中,当从StringBuffer输出文档时,以下语句获得不可读的代码.

objValue.AddMember("position", (*iter)->Position().c_str(), allocator);
Run Code Online (Sandbox Code Playgroud)

经过几个小时的挖掘,我想出了如何以正确的方式做到这一点.

Value tmp;
tmp.SetString( (*iter)->Position().c_str(), allocator);
objValue.AddMember("position", tmp, allocator);
Run Code Online (Sandbox Code Playgroud)

这是一个教程:http://miloyip.github.io/rapidjson/md_doc_tutorial.html