我正在尝试使用Boost Spirit解析JSON字符串,将JSON对象存储到递归数据结构中:
Value <== [null, bool, long, double, std::string, Array, Object];
Array <== [Value, Value, Value, ...];
Object <== ["name1": Value, "name2": Value, ...];
以下是我的代码:
#include <map>
#include <vector>
#include <string>
#include <boost/variant.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
struct JsonNull {};
struct JsonValue;
typedef std::map<std::string, JsonValue *> JsonObject;
typedef std::vector<JsonValue *> JsonArray;
struct JsonValue : boost::variant<JsonNull, bool, long, double, std::string, JsonArray, JsonObject>
{
};
JsonValue aval = JsonObject();
编译时我遇到了错误:
Error C2440: 'initializing' : cannot convert from 'std::map<_Kty,_Ty>' to 'JsonValue'
此外,如何安全地将JsonValue转换为JsonObject?当我尝试这样做时:
boost::get<JsonObject>(aval) = JsonObject();
这会导致运行时异常/致命故障。
非常感谢任何帮助。
编辑:
根据 @Nicol 的建议,我编写了以下代码:
struct JsonNull {};
struct JsonValue;
typedef std::map<std::string, JsonValue *> JsonObject;
typedef std::vector<JsonValue *> JsonArray;
typedef boost::variant<
JsonNull, bool, long, double, std::string,
JsonObject, JsonArray,
boost::recursive_wrapper<JsonValue>
> JsonDataValue;
struct JsonValue
{
JsonDataValue data;
};
我可以像这样轻松地处理JsonObject和JsonArray:
JsonValue *pJsonVal = new JsonValue();
boost::get<JsonObject>(pCurrVal->data).insert(
std::pair<std::string, JsonValue *>("key", pJsonVal)
);
boost::get<JsonArray>(pCurrVal->data).push_back(pJsonVal);
我发这篇文章是为了让大家都受益。