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

时间:2017-03-24 18:51:00

标签: 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;
}

当我使用命令amalgamate.py运行此代码(jsoncpp.cpp)时,我使用json.h生成jsoncpp.cpp和g++ 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

这里可能出现什么问题,如何解决这个问题?

提前致谢

1 个答案:

答案 0 :(得分:0)

终于解决了!!我正在写我的问题的答案,以帮助其他人 我没有正确链接库,所以它给了我那个错误。你可以用这种方式在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