如何使用Casablanca在现有的web :: json :: value对象中附加新的键值对?

时间:2016-12-22 10:58:55

标签: c++ json casablanca

我正在使用Casablanca C ++ REST库来处理JSON数据。这是我用来从头创建一个新的JSON对象并添加键值对的代码。

web::json::value temp;

// 1 - to add literal key-value pairs
temp[L"key1"] = web::json::value::string(U("value1"));

// 2 - to add key-value pairs of variables whose values I don't know, and are passed as std::string
temp[utility::conversions::to_string_t(key2)] = web::json::value::string(utility::conversions::to_string_t(value2)); 

这非常合适,我可以在新对象上使用它,并根据需要添加任意数量的键值对。

我的问题是我需要这些键追加到现有的web::json::value对象,而不是从头开始创建新的。我不知道现有对象的结构,因此代码必须更新与密钥对应的值(如果存在),或者添加新的键值对(如果它不存在)

当我尝试相同的代码时,除了我使用此行将temp分配给某个现有值:

web::json::value temp = m_value; //m_value is an existing object

我尝试使用运算符json::exception(使用上面使用的两种方法之一)访问temp时,我会得到[]

我如何实现我的需要?我搜索了SO,但我还没有找到卡萨布兰卡特定的问题答案。

1 个答案:

答案 0 :(得分:0)

我找到了一个对我有用的解决方法,但我不相信这是一个好方法。等待其他答案,但这可以帮助那些达到这个问题的人。

解决方法是创建一个新对象并添加新的键值对,然后迭代旧对象并逐个添加所有键。这可能有相当糟糕的表现。

web::json::value temp;
temp[key] = web::json::value::string(newvalue); // key and newvalue are of type utility::string_t

// m_value is the web::json::value which currently holds data
for (auto iter = m_value.as_object().cbegin(); iter != m_value.as_object().cend(); ++iter)
{
    const std::string jsonKey = utility::conversions::to_utf8string(iter->first);
    const web::json::value &jsonVal = iter->second;
    temp[utility::conversions::to_string_t(jsonKey)] = jsonVal;
}

m_value = temp;