首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我的项目应该读取一个json文件,但是生成一个错误。

我的项目应该读取一个json文件,但是生成一个错误。
EN

Stack Overflow用户
提问于 2021-12-05 10:08:50
回答 1查看 164关注 0票数 0

我已经为尝试JsonCpp库做了一个例子。

我已将其包括在我的项目中,项目内容如下:

代码语言:javascript
运行
复制
#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,其内容如下:

代码语言:javascript
运行
复制
{
    "Category" : "Technical",
    "Date" : "1 January 2021",
    "Name" : "Java2Blog",
    "first" : "Shishank",
    "last" : "Jain"
}

但是,当我编译和运行该项目时,它会生成以下错误:

代码语言:javascript
运行
复制
* Line 1, Column 1
  Syntax error: value, object or array expected.

我遵循了这个指南:https://java2blog.com/json-parser-cpp/

这是我第一次在C ++项目中使用json

EN

回答 1

Stack Overflow用户

发布于 2021-12-05 11:22:18

我已经解决了我的问题。

json文件已经在UTF-8中编码,并且文件路径是正确的。

我已经这样修改了我的代码:

代码语言:javascript
运行
复制
#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");
}

我为给大家带来的不便向大家道歉

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70233248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档