c++ - 使用 jsonCpp 库从 C++ 中的文件解析 json 时出错

标签 c++ json jsoncpp

我有一个类似这样的 JSON 文件

[{ 
 "movie_id": 1, 
 "rating": "9.3", 
 "votes": "1,318,626", 
 "description": "Two imprisoned men bond over a number ....", 
 "title": "The Shawshank Redemption", 
 "poster": "", 
 "release_date": "14 October 1994", 
 "metascore": "80", 
 "director": "Frank Darabont", 
 "storyline": "Andy Dufresne is a young and successful ...",
 "stars": [ "Tim Robbins", "Morgan Freeman", "Bob Gunton" ], 
 "year": "1994", 
 "genre": [ "Crime", "Drama" ], 
 "gallery": [ "unknown1394846836._CB379391227_.png", ], 
 "running_time": "142min"
 },
 {...},
 {...},...]

我想使用 jsonCpp 库解析上述文件 input.json 中的数据,这是我的代码

#include <bits/stdc++.h>
#include "json/json.h"
using namespace std;
int main(){
   Json::Value root;
   Json::Reader reader;

   ifstream file("input.json");
   file >> root;

   string title = root[0]["title"].asString();
   cout<<title;
   return 0;
}

当我使用命令 g++ 运行此代码 (jsoncpp.cpp) 时,我使用 amalgamate.py 生成 jsoncpp.cpp 和 json.h 文件jsoncpp.cpp 我收到以下错误

/tmp/ccx18K5p.o: In function `main':
jsoncpp.cpp:(.text+0x19): undefined referen to Json::Value::Value(Json::ValueType)'
jsoncpp.cpp:(.text+0x28): undefined reference to `Json::Reader::Reader()'
jsoncpp.cpp:(.text+0x57): undefined reference to `Json::operator>>   (std::istream&, Json::Value&)'
jsoncpp.cpp:(.text+0x68): undefined reference to `Json::Value::operator[] (int)'
jsoncpp.cpp:(.text+0x75): undefined reference to  `Json::Value::operator[](char const*)'
jsoncpp.cpp:(.text+0x8a): undefined reference to `Json::Value::asString[abi:cxx11]() const'
jsoncpp.cpp:(.text+0xdc): undefined reference to `Json::Value::~Value()'
jsoncpp.cpp:(.text+0x12b): undefined reference to `Json::Value::~Value()'
collect2: error: ld returned 1 exit status

这可能是什么问题,如何解决?

提前致谢

最佳答案

终于解决了!!我正在写我的问题的答案以帮助其他人 我没有正确链接库,所以它给了我那个错误。您可以在 C++ 中以这种方式链接任何外部库。

  1. 我的当前目录中有两个文件 json/json.hjsoncpp.cpp
  2. 创建一个新文件 main.cpp 并写下您使用该库的代码
  3. 不要编辑jsoncpp.cpp
  4. 包含 json.h 文件和 jsoncpp.cpp,如下面更新的代码所示。
  5. 然后运行 ​​g++ main.cpp

    #include <bits/stdc++.h>
    #include "json/json.h"
    #include "jsoncpp.cpp"
    using namespace std;
    int main(){
        Json::Value root;
        Json::Reader reader;
    
        ifstream file("input.json");
        file >> root;
    
        string title = root[0]["title"].asString();
        cout<<title<<"\n";
        return 0;
    }
    

    运行 g++ main.cpp 后的输出:

    The Shawshank Redemption
    

关于c++ - 使用 jsonCpp 库从 C++ 中的文件解析 json 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43007108/

相关文章:

c++ - JsonCpp 不能防止 uint64 溢出并且有奇怪的行为

c++ - 使用 json c++ 的输出在字段中获取奇怪的字符

c++ - 如何从 Json 中获取值

php - jQuery Ajax 返回 html 和 json 数据

java - Jersey - Moxy 在类属性中返回附加 json

c++ - 带有可移动、不可复制参数的 std::thread

c++ - system ("command") 产生错误;但它在直接从 Bash 提示符调用时有效

javascript - JSON 无效 token

c++ - 什么是数据区?

c++ - 如何避免许多 #ifdef 用于记录语句