使用 rapidjson 向地图添加值

Add values to map using rapidjson

我得到一个原始 json 字符串

{"vehicle": {"brand": "zonda","color": "blue"},"username": {"brand": "doyota","color": "red"}}

来自我拨打的电话。

我读到 rapidjson 是在 cpp 中解析 json 字符串的最佳方法。

所以我尝试这样做:

const char* json = data.c_str();
rapidjson::Document document;
if (document.Parse(json).HasParseError()) {

    cout << "has parse error" << endl;

    return 1;
}
else {
    assert(document.IsObject());
}

这里说 json 有一个解析错误。知道为什么会这样吗?

此外,一旦我能够解析值,我就想将它们作为键值对添加到标准映射中。任何人都可以指出正确的方向来继续这个吗?

这没有给我错误:

#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"

using namespace rapidjson;

int main() {
    Document d;
    std::string json = R"raw({"vehicle": {"brand": "zonda","color": "blue"},"username": {"brand": "doyota","color": "red"}})raw";

    if (d.Parse(json.c_str()).HasParseError()) {
        std::cout << "has error\n";
    } else {
        std::cout << "no error\n";
    }
}

尝试过 C++11 - C++20,一切似乎都很好。我猜你的数据中有一些非 UTF8 字符。