TanabeY / rapidjson

Automatically exported from code.google.com/p/rapidjson
MIT License
0 stars 0 forks source link

Utility function to convert documents to values #85

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
When implementing JSON-RPC we needed to switch between sending back a single 
object and an array of objects being returned as documents from multiple 
functions.  For this reason, we implemented a quick utility function to convert 
documents back into values.

/* Implementation */
template<class Allocator>
rapidjson::Value * document_to_value(rapidjson::Document & document, Allocator 
& alloc) {
  rapidjson::Value * rtn = new rapidjson::Value();

  if(document.IsObject()) {

    rtn->SetObject();
    for (rapidjson::Value::MemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) {
      rtn->AddMember(itr->name, itr->value, alloc);
    }
    return rtn;

  } else if (document.IsArray()) {

    rtn->SetArray();
    for (int64_t i = 0; i < document.Size(); i++) {
      rtn->PushBack(document[i], alloc);
    }
    return rtn;

  } else {

    delete rtn;
    return NULL;

  }
}

/* Usage */
int
main(int argc, char *argv[]) 
{
  rapidjson::Document outer_arr, outer_obj;

  rapidjson::Value inner_obj, inner_data;

  inner_data.SetString("data here", outer_obj.GetAllocator());

  inner_obj.SetObject();
  inner_obj.AddMember("inner_data", inner_data, outer_obj.GetAllocator());

  outer_obj.SetObject();
  outer_obj.AddMember("inner", inner_obj, outer_obj.GetAllocator());

  rapidjson::Value * outer_obj_copy = document_to_value(outer_obj, outer_arr.GetAllocator());

  outer_arr.SetArray();
  outer_arr.PushBack(*outer_obj_copy, outer_arr.GetAllocator());

  rapidjson::FileStream f(stdout);
  rapidjson::PrettyWriter<rapidjson::FileStream> writer(f);
  outer_arr.Accept(writer);

  return 0;
}

Original issue reported on code.google.com by robert.c...@gmail.com on 2 Aug 2013 at 8:38

GoogleCodeExporter commented 8 years ago

Original comment by milo...@gmail.com on 30 Jun 2014 at 4:47

GoogleCodeExporter commented 8 years ago
This shall be easily archived by a new API GenericValue::Swap(). The document's 
root and a value can be swapped as well.

https://github.com/miloyip/rapidjson/commit/9ed11d29a24ab0ae53e6868fcaf3337a56b7
3555

Original comment by milo...@gmail.com on 13 Jul 2014 at 4:25