JSONCPP无法正确读取文件

时间:2010-11-25 01:35:05

标签: c++ json

所以我最近安装了JSONCPP,出于某种原因,当我尝试这段代码时,它给了我错误:

#include <json.h>
#include <iostream>
#include <fstream>

int main(){
    bool alive = true;
    while (alive){
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::string test = "testis.json";
    bool parsingSuccessful = reader.parse( test, root, false );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << reader.getFormatedErrorMessages()
               << "\n";
    }

    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    alive = false;


    }
    return 0;
}

这是文件:

{
"encoding" : "lab"
}

它表示第1行第1列存在语法错误,并且必须存在值,对象或数组。任何人都知道如何解决这个问题?

编辑:从pastebin

更改为当前代码

3 个答案:

答案 0 :(得分:27)

请参阅Json::Reader::parse文档。对于那个重载,字符串需要是实际文档,而不是文件名。

您可以使用istream overload代替ifstream

std::ifstream test("testis.json", std::ifstream::binary);
编辑:我得到了它的工作:

#include "json/json.h"
#include <iostream>
#include <fstream>

int main(){
    bool alive = true;
    while (alive){
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::ifstream test("testis.json", std::ifstream::binary);
    bool parsingSuccessful = reader.parse( test, root, false );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << reader.getFormatedErrorMessages()
               << "\n";
    }

    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    alive = false;
    }
    return 0;
}

答案 1 :(得分:3)

#include "json/json.h"
#include <iostream>
#include <fstream>

int main(){
    Json::Value root;   // will contain the root value after parsing.
    std::ifstream stream("testis.json", std::ifstream::binary);
    stream >> root;
    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    return 0;
}

或更一般地说:

#include "json/json.h"
#include <iostream>
#include <fstream>

int main(){
    Json::Value root;   // will contain the root value after parsing.
    Json::CharReaderBuilder builder;
    std::ifstream test("testis.json", std::ifstream::binary);
    std::string errs;
    bool ok = Json::parseFromStream(builder, test, &root, &errs);
    if ( !ok )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << errs << "\n";
    }

    std::string encoding = root.get("encoding", "UTF-8" ).asString();
    std::cout << encoding << "\n";
    return 0;
}

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/namespace_json.html

答案 2 :(得分:-12)

json不能包含换行符。试试这个:

{"encoding": "lab"}

您可能需要确保在没有最终换行符的情况下保存文件。

编辑:也许您的解析器可以容忍换行符,但有些则不会。如果其他答案不起作用,可以试试