QStringList Json::getStringList(const QString &path, const QJsonObject &fromNode) const { QStringList result; QJsonArray array = getJsonValue(path, fromNode).toArray(); for (QJsonArray::const_iterator iter = array.begin(); iter != array.end(); ++iter) { QJsonValue value = *iter; result << value.toString(); } return result; }
clan::JsonValue& JSONReader::getJsonValue(std::string const &path, clan::JsonValue& root) { if (path.empty()) return root; auto const end = path.find_first_of('.'); auto const ind = path.find_first_of('['); bool has_dot = end != std::string::npos; bool has_array = ind != std::string::npos; bool parse_array = has_array && (has_dot ? (ind < end) : true); // Get member with the `part' identifer std::string parsed_part = path.substr(0, end); std::string member_part = path.substr(0, parse_array ? ind : end); auto node = root.get_members().find(member_part); if (node == root.get_members().end()) throw std::out_of_range("Could not find member '" + member_part + "'"); if (parse_array) { if (node->second.is_array() == false) throw new clan::JsonException("Member '" + member_part + "' is not an array."); auto ind_end = parsed_part.find_first_of(']'); if (ind_end == std::string::npos) throw new clan::JsonException("Expected closing bracket ']' in '" + parsed_part + "'."); if (ind_end <= ind) throw new clan::JsonException("Unexpected ']' in '" + parsed_part + "'."); std::string ind_part = parsed_part.substr(ind + 1, ind_end - 2); if (ind_part.empty()) throw new clan::JsonException("Index enumerator in '" + parsed_part + "' is empty."); auto member = (node->second.get_items())[std::stoul(ind_part)]; return has_dot ? getJsonValue(path.substr(end + 1), member) : member; } return has_dot ? getJsonValue(path.substr(end + 1), node->second) : node->second; }
QString QVariantMapToString(QVariantMap& data) { QString json; bool first = true; json = "{"; QMapIterator<QString, QVariant> i(data); while (i.hasNext()) { i.next(); json += (first ? "" : ", ") + QString("\"%1\": %2").arg(i.key()).arg(getJsonValue(i.value().toString())); if (first) first = false; } json += "}"; return json; }
int Json::getInt(const QString &path, int def, const QJsonObject &fromNode) const { return getJsonValue(path, fromNode).toInt(def); }
QJsonObject Json::getJsonObject(const QString &path, const QJsonObject &fromNode) const { return getJsonValue(path, fromNode).toObject(); }
QString Json::getString(const QString &path, const QString &def, const QJsonObject &fromNode) const { return getJsonValue(path, fromNode).toString(def); }
double Json::getDouble(const QString &path, double def, const QJsonObject &fromNode) const { return getJsonValue(path, fromNode).toDouble(def); }
bool Json::getBool(const QString &path, bool def, const QJsonObject &fromNode) const { return getJsonValue(path, fromNode).toBool(def); }