我有一个类似这样的 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++ 中以这种方式链接任何外部库。
- 我的当前目录中有两个文件
json/json.h
和jsoncpp.cpp
- 创建一个新文件
main.cpp
并写下您使用该库的代码 - 不要编辑
jsoncpp.cpp
- 包含
json.h
文件和jsoncpp.cpp
,如下面更新的代码所示。 然后运行
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/