7

我正在尝试将使用 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);

只是发布,以便每个人都可以从中受益。

4

1 回答 1

7

您必须使用递归包装器(并且您不应该派生自boost::variant):

struct JsonValue;

typedef boost::variant</*types*/, boost::recursive_wrapper<JsonValue> > JsonDataValue;

struct JsonValue
{
    JsonDataValue value;
};

要使 Boost.Spirit 采用 JsonValue,您需要编写其中一个 Fusion 适配器以将原始变体类型调整为结构。


此外,如何安全地将 JsonValue 转换为 JsonObject?当我尝试这样做时:

这不是变体的工作方式。如果要将它们设置为一个值,只需像设置任何其他值一样设置它们:

JsonValue val;
val.value = JsonValue();
于 2011-07-03T07:39:08.993 回答