C++ 字符串包含----device-stream-boundary-- Content-Type: application/json Content-Length: 75 X-If-Encrypt: 0 {"type":"response", "seq":0, "params":{"error_code":0, "session_id":"157"}} 字符串解析出session_id
时间: 2023-07-08 12:49:04 浏览: 79
可以使用字符串的查找和截取操作来获取 session_id。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string response_str = "----device-stream-boundary-- Content-Type: application/json Content-Length: 75 X-If-Encrypt: 0 {\"type\":\"response\", \"seq\":0, \"params\":{\"error_code\":0, \"session_id\":\"157\"}}";
// 查找 JSON 字符串的起始位置
size_t json_start = response_str.find('{');
if (json_start == std::string::npos) {
std::cout << "JSON string not found!" << std::endl;
return -1;
}
// 截取 JSON 字符串
std::string json_str = response_str.substr(json_start);
// 解析 JSON 字符串并获取 session_id
size_t session_id_start = json_str.find("\"session_id\":");
if (session_id_start == std::string::npos) {
std::cout << "session_id not found!" << std::endl;
return -1;
}
session_id_start += std::string("\"session_id\":").size();
size_t session_id_end = json_str.find(',', session_id_start);
if (session_id_end == std::string::npos) {
std::cout << "Invalid JSON format!" << std::endl;
return -1;
}
std::string session_id = json_str.substr(session_id_start, session_id_end - session_id_start);
std::cout << "Session ID: " << session_id << std::endl;
return 0;
}
```
输出结果为:
```
Session ID: "157"
```
需要注意的是,获取到的 session_id 包含双引号,需要根据实际情况进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)