我已经为尝试JsonCpp库做了一个例子。
我已将其包括在我的项目中,项目内容如下:
#include <cstdlib>
#include <string>
#include <fstream>
#include <iostream>
#include <json\value.h>
#include <json\json.h>
using namespace std;
int main()
{
Json::Reader reader; //for reading the data
Json::Value newValue; //for modifying and storing new values
Json::StyledStreamWriter writer; //for writing in json files
//opening file using fstream
ifstream file("items.json");
// check if there is any error is getting data from the json file
if (!reader.parse(file, newValue)) {
cout << reader.getFormattedErrorMessages();
exit(1);
}
cout << newValue["Category"] << endl;
file.close();
system("pause");
}
json文件名为items.json,其内容如下:
{
"Category" : "Technical",
"Date" : "1 January 2021",
"Name" : "Java2Blog",
"first" : "Shishank",
"last" : "Jain"
}
但是,当我编译和运行该项目时,它会生成以下错误:
* Line 1, Column 1
Syntax error: value, object or array expected.
我遵循了这个指南:https://java2blog.com/json-parser-cpp/
这是我第一次在C ++项目中使用json
发布于 2021-12-05 11:22:18
我已经解决了我的问题。
json文件已经在UTF-8中编码,并且文件路径是正确的。
我已经这样修改了我的代码:
#include <fstream>
#include <iostream>
#include <json\json.h>
using namespace std;
int main()
{
ifstream file;
file.open("items.json");
if (!file)
{
cout << "File non esiste" << endl;
}
else
{
Json::Reader reader; //for reading the data
Json::Value value; //for modifying and storing new values
reader.parse(file, value);
cout << value["Category"] << endl;
}
file.close();
system("pause");
}
我为给大家带来的不便向大家道歉
https://stackoverflow.com/questions/70233248
复制相似问题