2016-12-22 52 views
2

我正在使用卡萨布兰卡C++ REST库来处理JSON数据。这是我用来从头创建一个新的JSON对象并添加键值对的代码。如何在使用卡萨布兰卡的现有web :: json :: value对象中追加新的键值对?

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 

我只要我尝试与运营商[]访问temp得到json::exception(使用我上面使用的两种方法)。

我该如何实现我所需要的?我已经搜索过,但我没有找到卡萨布兰卡特定的答案来解决我的问题。

回答

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; 
相关问题