JSONCPP Не правильно читает файлы - PullRequest
11 голосов
/ 25 ноября 2010

Итак, я недавно установил 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 ]

27 голосов
/ 25 ноября 2010

См. Документацию Json::Reader::parse.Для этой перегрузки строка должна быть фактическим документом, а не именем файла.

Вы можете использовать перегрузку istream вместо 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;
}
3 голосов
/ 14 февраля 2015
#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

0 голосов
/ 25 ноября 2010

json не может содержать переводы строк. Попробуйте вместо этого:

{"encoding": "lab"}

Возможно, вам нужно убедиться, что файл сохранен без последней новой строки.

РЕДАКТИРОВАТЬ : Возможно, ваш парсер допускает переводы строки, но некоторые этого не делают. Что-то, чтобы попробовать, если другие ответы не работают

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...