c++ - boost 变体 : How to model JSON?

标签 c++ json boost boost-spirit boost-variant

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

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

最佳答案

你必须使用递归包装器(你不应该从 boost::variant 派生):

struct JsonValue;

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

struct JsonValue
{
    JsonDataValue value;
};

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


Moreover, how to safely cast JsonValue to JsonObject? When I try doing:

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

JsonValue val;
val.value = JsonValue();

关于c++ - boost 变体 : How to model JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561643/

相关文章:

c++ - gcc exec if 和 else 也是...这是一个错误吗?

c++ - 匹配开始/结束分析调用

c++ - 关于CMake

javascript - angularjs如何在html模板中的json对象中进行搜索

c++ - 在同一硬件单元上创建多个线程

c++ - 定义具有任意跨度的指针

json - Instagram 最新帖子 API 突然停止工作

json - Swift 4 Decodable - 动态类型、键和属性

c++ - 如何将 'CDT' 转换为 time_zone_ptr

c++ - 编译器特定错误 : can't match function with const arguments