【问题标题】:How to extract specific data returned from web::json::value::serialize() with cpprestsdk/casablanca如何使用 cpprestsdk/casablanca 提取从 web::json::value::serialize() 返回的特定数据
【发布时间】:2018-04-20 03:33:29
【问题描述】:

我有这个代码:

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 字段 和 status[]字段的单个数据(即数组)

来自web::json::value::serialize()返回的数据?

谢谢。

【问题讨论】:

  • serialize()的返回类型是什么?
  • 返回json类型

标签: c++ json cpprest-sdk


【解决方案1】:

您不必调用 serialize 来访问 json 值。一旦你有一个json::value,它包含一个json对象,你可以遍历它来获取内部对象和数组,如json::value的:

json::value jvalue; //this is your initial value

// this new value will hold the whole 'data' object:
json::value data = jvalue.at(U("data")); 

// read `timestamp` array from `data` and directly read 
// the item at index 0 from it:
json::value timestamp = data.at(U("timestamp")).at(0);

// from `timestamp` (first item of timestmap array`)
json::value id = timestamp.at(U("_id"));

// print `id` as string
std::wcout << id.as_string() << std::endl;

// read `status` array first item and print it as string
json::value status = timestamp.at(U("status"));
std::wcout << status.at(0).as_string() << std::endl;

您可以从上面的代码中猜到,对at 的调用可以链接在一起:

// read the `_id` value at once and print it as string
std::wcout << jvalue.at(U("data")).at(U("timestamp")).at(0).at(U("_id")).as_string() << std::endl;

一切都很好解释here

【讨论】:

  • 您好,Paolo 先生,谢谢。我想这应该可以工作,但是当我尝试运行程序时,控制台出现没有输出,并且 json.h 文件被打开到 ide,并显示一些消息“MathClient.exe 中 0x00007FF8B7C34008 处的未处理异常:Microsoft C++ 异常:web: :json::json_exception 在内存位置 0x00000001000FF3C0。"
  • 这是我的完整代码:github.com/Microsoft/cpprestsdk/issues/739 谢谢。
  • 您有一个未处理异常。将整个代码包含在 try 块中,并尝试使用 catch(const std::exception &amp;e) 捕获异常,看看出了什么问题。
  • 我试过了,但没有错误显示,也没有输出。
  • catch 块内有一个std::cout &lt;&lt; e.what() &lt;&lt; std::endl;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
相关资源
最近更新 更多