Rapidjson-将密钥更改为另一个值 [英] rapidjson - change key to another value

查看:480
本文介绍了Rapidjson-将密钥更改为另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Rapidjson的问候世界.如何将键"hello"更改为"goodbye"并从json获取字符串?我的意思是我想解析json,更改一些键并像{"goodbye" : "world"}一样取回json字符串.

Here is the hello world of rapidjson. How can I change key "hello" to "goodbye" and get string from the json? I mean I want to parse json, change some keys and get json string back like {"goodbye" : "world"}.

const char json[] = "{ \"hello\" : \"world\" }";

rapidjson::Document d;
d.Parse<0>(json);

推荐答案

  const char *json = R"({"hello": "world"})";
  rapidjson::Document d;
  d.Parse<0> (json);

  rapidjson::Value::Member* hello = d.FindMember ("hello"); if (hello) {
    d.AddMember ("goodbye", hello->value, d.GetAllocator());
    d.RemoveMember ("hello");
  }

  typedef rapidjson::GenericStringBuffer<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> StringBuffer;
  StringBuffer buf (&d.GetAllocator());
  rapidjson::Writer<StringBuffer> writer (buf, &d.GetAllocator());
  d.Accept (writer);
  json = buf.GetString();

P.S.您之后可能应该复制json,因为它的内存将与d一起释放.

P.S. You should probably copy the json afterwards because its memory will be freed together with d.

P.P.S.您也可以就地替换字段名称,而无需将其删除:

P.P.S. You can also replace the field name in-place, without removing it:

rapidjson::Value::Member* hello = d.FindMember ("hello");
if (hello) hello->name.SetString ("goodbye", d.GetAllocator());

或者在迭代过程中:

for (auto it = d.MemberBegin(); it != d.MemberEnd(); ++it)
  if (strcmp (it->name.GetString(), "hello") == 0) it->name.SetString ("goodbye", d.GetAllocator());

这篇关于Rapidjson-将密钥更改为另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆