Rapidjson::Type的开关大小写.我尝试解析的

Switch case for Rapidjson::Type

本文关键字:大小写 Type 开关 Rapidjson      更新时间:2023-10-16

JSON看起来像这样:

{
   "testBool": true,
   "testString": "eu"
}

而且我目前的解析器看起来真的很丑,真的感觉有一种更优雅的方法可以解决这个问题。我尝试使用 document.GetObject().GetType() 研究开关盒的rapidjson::Type,但它不能提供与使用Get%TypeName%()函数可以实现的相同类型精度。 hashmap只不过是std::unordered_map<std::string, std::any>的包装纸。

rapidjson::Document document;
document.Parse(tmp_string.c_str());
for (auto& member : document.GetObject())
{
if (member.value.IsBool())
{
   hashmap->addEntry<bool>(member.name.GetString(), member.value.GetBool());
}
else if (member.value.IsString())
{
   hashmap->addEntry<std::string>(member.name.GetString(), member.value.GetString());
}
else if (member.value.IsInt())
{
   hashmap->addEntry<int>(member.name.GetString(), member.value.GetInt());
}
.....
//And so on
.....
}

我目前的解析器看起来真的很丑

美在被(呃)持有者的眼中...这是我的代码:

static void
printField(const Value& e, const string& fld, bool print_newline = true) {
    const Value &v = fld.empty() ? e : e[fld];
    if (print_newline)
        cout << endl << "t";
    if (not fld.empty())
        cout << fld << ":  ";
    if ( /* custom stuff required? */ ) {
        // Do custom stuff
    else {
       switch (v.GetType()) {
        case kNullType:
            cout << "Null";
            break;
        case kFalseType:
        case kTrueType:
            cout << v.GetBool();
            break;
        case kObjectType: {
            bool first = true;
            cout << "{ ";
            for (const auto &subfield: v.GetObject()) {
                if (first)
                    first = false;
                else
                    cout << ", ";
                printField(v, subfield.name.GetString(), false);
            }
            cout << " }";
            break;
        }
        case kArrayType: {
            bool first = true;
            cout << "[ ";
            for (const auto &arrEntry: v.GetArray()) {
                if (first)
                    first = false;
                else
                    cout << ", ";
                printField(arrEntry, "", false);
            }
            cout << " ]";
            break;
        }
        case kStringType:
            cout << v.GetString();
            break;
        case kNumberType:
            if (v.IsInt64())
                cout << v.GetInt64();
            else if (v.IsUint64())
                cout << v.GetUint64();
            else
                cout << v.GetDouble();
            break;
        default:
            stringstream msg;
            msg << "Unexpected RapidJSON Value type: " << v.GetType();
            throw logic_error(msg.str());
        }
    }
}

这使用字符串化的东西来解决一些问题,但是,如果你不喜欢这样,你可以手动获得相同的效果。 它使用级联if细分IsNumber情况;如果您需要更多分辨率,可以将其他情况添加到其中。