rapidjson - change object - add element/item

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

how do I add a member to a rapidjson object and then print it?

for example add

 itemtwo => "world" ; 

to this object:

{"itemone":"hello"}   

I tried

 char buff[] = "{\"itemone\":\"hello\"}";  rapidjson::Document json_obj;  if(json_obj.Parse<0>(buff.c_str()).HasParseError() == false){             json_obj["itemtwo"].SetString("world");     rapidjson::StringBuffer strbuf;     rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);     json_obj.Accept(writer);     cout<<strbuf.GetString()<<endl;  } 

I get the following output:

{"itemone":"hello"}   

meaning no change. What am I doing wrong?

回答1:

json_obj["itemtwo"] can only find member with that name, which is not exist. It does not create a new entry (as in std::map).

To manipulate objects, use AddMember() and other related member functions, e.g.

json_obj.AddMember("itemone", "hello", json_obj.GetAllocator()); 

You may refer to rapidjson user guide and/or the tutorial.cpp in the package.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!