访问C++中的JSON值

Accessing JSON values in C++

本文关键字:JSON 中的 C++ 访问      更新时间:2023-10-16

我正试图为一个小型应用程序编写一个程序,在虚幻引擎中导航您的本地光盘。我已经使用Gradle构建了一个REST服务器,长话短说,我得到了一个带有机器目录的JSON。我想提取特定的目录名称,以字符串(特别是FText,但在这里不太重要)数组的形式返回。

我在github上找到了一个由nLohmann创建的库(https://github.com/nlohmann/json)这似乎是在c++中处理JSON的最佳方式。然而,就我的一生而言,我不知道如何提取目录名。我尝试了一个迭代器和一个简单的.value()调用。

代码和JSON示例如下,如有任何见解,将不胜感激。

char buffer[1024];
FILE *lsofFile_p = _popen("py C:\Users\jinx5\CWorkspace\sysCalls\PullRoots.py", "r");
fgets(buffer, sizeof(buffer), lsofFile_p);
_pclose(lsofFile_p);
std::string rootsJson(buffer);
string s = rootsJson.substr(1);
s = ReplaceAll(s, "'", "");
//here my string s will contain: [{"description":"Local Disk","name":"C:\"},{"description":"Local Disk","name":"D:\"},{"description":"CD Drive","name":"E:\"}]

//These are two syntax examples I found un nlohmann's docs, neither seems to work 
auto j = json::parse(s);
string descr = j.value("description", "err");

我认为您的问题来自于文本字符串中的数量。C:\:C:\\需要5个

下面是一个工作示例:

#include "json.hpp"
#include <string>
using namespace std;
using json = nlohmann::json;
int main(){
    json j = json::parse("[{"description":"Local Disk","name":"C:\\"},{"description":"Local Disk","name":"D:\\"},{"description":"CD Drive","name":"E:\\"}]");
    cout << j.is_array() << endl;
    for (auto& element : j) {
      std::cout << "description : " << element["description"] << " | " << " name : "  << element["name"] << 'n';
    }
    return 0;
}