[英]Accessing JSON values in C++
我正在嘗試編寫一個程序,用於在小型應用程序的Unreal Engine中導航您的本地光盤。 我已經使用Gradle組裝了一個REST服務器,總之,我得到了帶有機器目錄的JSON。 我想提取特定的目錄名稱,以字符串(特別是FText,但在這里不太重要)數組的形式返回。
我在github( https://github.com/nlohmann/json )上找到了nLohmann創建的庫,這似乎是在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:\\\\
您需要5 \\
: C:\\\\\\\\\\
。
這是一個工作示例:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.