下面将提供一个完整的json处理相关的工具类,适用于所有类型的数据。可以通过下面链接获取文件
部分代码展示:
bool asBool() const {
if (type_ != Type::Boolean) return false;
else return boolVal;
}
int asInt() const { // 新增
if (type_ == Type::Integer) return intVal;
if (type_ == Type::Number) return static_cast<int>(numVal);
else return -1;
}
double asNumber() const {
if (type_ == Type::Integer) return intVal;
if (type_ == Type::Number) return numVal;
else return -1;
}
const std::string& asString() const {
static const std::string emptyString = "";
if (type_ != Type::String) return emptyString;
else return *strVal;
}
const Array& asArray() const {
if (type_ != Type::Array) throw std::runtime_error("Not an array");
return *arrVal;
}
const Object& asObject() const {
if (type_ != Type::Object) throw std::runtime_error("Not an object");
return *objVal;
}
使用流程
解析数据
string jsonStr = httpPtr->mResponse;
SimpleJson::Json root;
root = SimpleJson::Json::parse(jsonStr);
int responseCode = root.asObject().at("code").asInt();
string message = root.asObject().at("message").asString();
组成json
SimpleJson::Json::Object jsonObj;
// 添加所有字段到 JSON 对象
jsonObj["size"] = 10;
jsonObj["page"] = idx;
jsonObj["mid"] = id;
// 创建 Json 对象并转换为字符串
SimpleJson::Json json(jsonObj);