Problems encountered with int to string conversion in rapidjson

demand

I want to save an array in the form of Object, so the index needs to be converted from integer to string

problem

1. How to convert gracefully

Finally, I did not find a suitable method

// 有问题的写法
doc.AddMember(rapidjson::StringRef(std::to_string(i).c_str()), strContent, allocator);

// 正确的写法
rapidjson::Value strIndex;
strIndex.SetString(std::to_string(i).c_str(), allocator);
doc.AddMember(strIndex, strContent, allocator);
  • Test code
    rapidjson::Value strIndex;
    rapidjson::Value strContent(rapidjson::kStringType);
    std::string strIndex1;
    for (int i = 0; i <2; ++i)
    {
        strContent.SetString("test");
        
        // way1: error
        //doc.AddMember(rapidjson::StringRef(std::to_string(i).c_str()), strContent, allocator);

        // way2: error
        strIndex1 = std::to_string(i);
        doc.AddMember(rapidjson::StringRef(strIndex1.c_str()), strContent, allocator);

        // way3: correct
        strIndex.SetString(std::to_string(i).c_str(), allocator);
        doc.AddMember(strIndex, strContent, allocator);
    }

2. The garbled form of \ 0000

The results obtained using the three methods are as follows:

// way1
{
    "\u0000": "test",
    "\u0000": "test"
}
// way2
{
    "1": "test",
    "1": "test"
}
// way3
{
    "0": "test",
    "1": "test"
}

Reason explanation:
Refer to [1], the first two methods use StringRef , and this is just a pointer to the string, so different results appear:

  • Method 1, the temporary variable is destroyed after the loop, so it is not recognized as a string;
  • Method 2, two loops refer to the same address, so the index is the last one
  • Method 3 is to guess the copy method. In C ++, it is value transfer or deep copy, which is a safe way.

to sum up

  1. The method of using rapidjson to convert a string to int is still a bit verbose
  2. Use string to be especially careful when StringRef pit

reference

[1] A little pit used by string in rapidjson

Published 41 original articles · praised 7 · 20,000+ views

Guess you like

Origin blog.csdn.net/pkxpp/article/details/88791695