如何使用cpprestsdk/casablanca提取JSON对象中的特定数据(如_id)
提取cpprestsdk(Casablanca)JSON中的特定字段示例
问题背景
我使用cpprestsdk(Casablanca)开发,现有代码wcout << jvalue.serialize() << endl;会打印完整的JSON数据:
{ "data": { "timestamp": [ { "_id": "5ad93fc48084e1089cd9667b", "staff_id": 172, "staff_name": "Michael Edano", "time_in": "2018-04-20T01:17:56.787Z", "time_out": null, "status": ["Leave","Vacation","Absent"], "createdAt": "2018-04-20T01:17:56.790Z", "updatedAt": "2018-04-20T01:17:56.790Z", "__v": 0 } ], "success": true } }
需要提取其中特定字段(如_id)的示例代码。
解决方案
没问题,我来帮你搞定cpprestsdk里提取JSON字段的事儿!cpprestsdk的JSON API支持逐层访问节点,我们可以用安全的方式提取目标字段,下面是完整的示例代码:
#include <cpprest/json.h> #include <iostream> #include <utility> using namespace web; using namespace web::json; using namespace std; int main() { // 假设你已经通过接口响应或其他方式获取到了jvalue对象 value jvalue = value::parse(U(R"({ "data": { "timestamp": [ { "_id": "5ad93fc48084e1089cd9667b", "staff_id": 172, "staff_name": "Michael Edano", "time_in": "2018-04-20T01:17:56.787Z", "time_out": null, "status": ["Leave","Vacation","Absent"], "createdAt": "2018-04-20T01:17:56.790Z", "updatedAt": "2018-04-20T01:17:56.790Z", "__v": 0 } ], "success": true } })")); try { // 1. 逐层获取JSON节点:先拿到data节点 value data_node = jvalue.at(U("data")); // 2. 获取timestamp数组(需要转成array类型) array timestamp_array = data_node.at(U("timestamp")).as_array(); // 3. 先判断数组非空,再取第一个元素 if (!timestamp_array.empty()) { value timestamp_item = timestamp_array[0]; // 4. 提取_id字段,转成字符串类型 utility::string_t target_id = timestamp_item.at(U("_id")).as_string(); // 打印提取结果 wcout << U("提取到的_id: ") << target_id << endl; } else { wcout << U("timestamp数组为空,无法提取字段") << endl; } } catch (const json_exception& e) { // 处理节点不存在、类型不匹配等异常情况 wcout << U("JSON解析出错: ") << e.what() << endl; } return 0; }
关键细节说明
- 安全访问节点:用
at(U("key"))方法访问节点,当键不存在或者类型不匹配时会抛出json_exception,适合需要严格校验的场景。 - 避免意外修改原JSON:如果不想抛出异常,可以先用
contains(U("key"))判断键是否存在,再用operator[]访问(注意:operator[]如果键不存在会自动插入默认值,可能修改原JSON对象)。 - 类型转换:数组类型要通过
as_array()转换,字符串类型用as_string()转成utility::string_t(对应宽字符串,适配cpprestsdk的编码)。
内容的提问来源于stack exchange,提问作者noyruto88
相关产品推荐
相关产品推荐

